是否可以使用PropertyInfo创建通用选择器?

时间:2019-05-13 03:38:22

标签: c#

我正在尝试创建一个函数,该函数将对任何给定对象的IEnumerable进行处理

    public class Sales
    {
        public float Next { get; set; }
        public string ProductId { get; set; }
        public float Year { get; set; }
        public float Month { get; set; }
        public float Units { get; set; }
    }

,您可以看到其中包含浮点数和字符串的属性 现在我想要的是从这些float属性中计算最小最大值

public static IEnumerable<T> GenericSelector<T>(this IEnumerable<T> dataset)
{
    foreach (var property in typeof(T).GetProperties())
    {
        if(property.PropertyType == typeof(float))
        {
            var min = dataset.Min(x => /*reflection from property variable*/);
            var max = dataset.Max(x => /*reflection from property variable*/;
            /** more calculation of min max from here **/
        }
    }
}

在这种情况下是否可以将属性反映回选择器?

1 个答案:

答案 0 :(得分:0)

您可以使用PropertyInfo.GetValue

foreach (var property in typeof(T).GetProperties())
{
    if(property.PropertyType == typeof(float))
    {
        var min = dataset.Min(x => (float)property.GetValue(x));
        var max = dataset.Max(x => (float)property.GetValue(x));
        // ...
    }
}