gpt4 book ai didi

c# - 使用属性名称的字符串表示在 LINQ C# 中计算平均值

转载 作者:太空宇宙 更新时间:2023-11-03 18:47:49 25 4
gpt4 key购买 nike

我需要计算调查列表中的一大堆平均值。调查有很多属性是 int 和 double 值。我正在创建一个业务对象来处理所有计算(大约有 100 个),我不想编写 100 种不同的方法来查找特定属性的平均值。

我希望能够让 UI 传递一个字符串(代表属性)并让业务对象返回该属性的平均值。

所以,就像...

int AverageHeightInInches = MyObject.GetIntAverage("HeightInInches");...然后有linq代码来计算结果。

谢谢!

最佳答案

我创建了这个小示例,它使用 System.Linq.Expression 命名空间来创建一个可以根据属性名称计算平均值的函数。函数可以缓存起来供以后使用,反射只用于创建函数,而不是每次执行函数时。

编辑:我删除了现有的反射示例并更新了当前示例以显示遍历属性列表的能力。

static class Program
{
static void Main()
{
var people = new List<Person>();

for (var i = 0; i < 1000000; i++)
{
var person = new Person { Age = i };

person.Details.Height = i;
person.Details.Name = i.ToString();

people.Add(person);
}

var averageAgeFunction = CreateIntegerAverageFunction<Person>("Age");
var averageHeightFunction = CreateIntegerAverageFunction<Person>("Details.Height");
var averageNameLengthFunction = CreateIntegerAverageFunction<Person>("Details.Name.Length");

Console.WriteLine(averageAgeFunction(people));
Console.WriteLine(averageHeightFunction(people));
Console.WriteLine(averageNameLengthFunction(people));
}

public static Func<IEnumerable<T>, double> CreateIntegerAverageFunction<T>(string property)
{
var type = typeof(T);
var properties = property.Split('.'); // Split the properties

ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
Expression expression = parameterExpression;

// Iterrate over the properties creating an expression that will get the property value
for (int i = 0; i < properties.Length; i++)
{
var propertyInfo = type.GetProperty(properties[i]);
expression = Expression.Property(expression, propertyInfo); // Use the result from the previous expression as the instance to get the next property from

type = propertyInfo.PropertyType;
}

// Ensure that the last property in the sequence is an integer
if (type.Equals(typeof(int)))
{
var func = Expression.Lambda<Func<T, int>>(expression, parameterExpression).Compile();
return c => c.Average(func);
}

throw new Exception();
}
}

public class Person
{
private readonly Detials _details = new Detials();

public int Age { get; set; }
public Detials Details { get { return _details; } }
}

public class Detials
{
public int Height { get; set; }
public string Name { get; set; }
}

关于c# - 使用属性名称的字符串表示在 LINQ C# 中计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2924940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com