C# Linq使用属性名相等

C# Linq使用属性名相等,c#,linq,C#,Linq,我有一个从用户数据源读入的类: Item Warehouse Customer Forecast_4_2018 Forecast_5_2018 以此类推-我正在使用这些数据进行一些计算,并希望在当前月份动态选择要使用的“预测”属性 int year, int month PropertyInfo[] properties = typeof(CombinedForecast).GetProperties(); PropertyInfo useThisForecast = null; foreac

我有一个从用户数据源读入的类:

Item
Warehouse
Customer
Forecast_4_2018
Forecast_5_2018
以此类推-我正在使用这些数据进行一些计算,并希望在当前月份动态选择要使用的“预测”属性

int year, int month
PropertyInfo[] properties = typeof(CombinedForecast).GetProperties();
PropertyInfo useThisForecast = null;
foreach (PropertyInfo property in properties)
{
    if(property.Name.ContainsAll(year.ToString(), month.ToString()))
    {
        useThisForecast = property;                   
    }       
}
因此,在这种情况下
使用ThisForecast==Forecast\u 4\u 2018

我有一个LINQ查询来对数据进行分组并求和数量,但我想指定要按属性名称求和的属性

var results = from a in CombinedForecast
    group a by new
    {
        a.ItemNumber,
        a.ShipFromNumber,
        a.ShipToNumber
    } into grouping
    select new SummedOrders
    {
        SummedQuantity = grouping.Sum(x => x.Forecast_4_2018.Value /*x.GetType().Name.Equals(useThisForecast.Name).Value */ ),
        Item = grouping.Key.ItemNumber,
        Warehouse = grouping.Key.ShipFromNumber.ParseInt(),
        CustomerNumber = grouping.Key.ShipToNumber
    };

return results.ToList();
在下面的代码中,我试图使用属性的名称,而不是设置它,但是我无法正确地获取语法

 SummedQuantity = grouping.Sum(x => x.Forecast_4_2018.Value /*x.GetType().Name.Equals(useThisForecast.Name).Value */

您需要使用
PropertyInfo.GetValue
方法从适当类型的对象检索相应的属性值:

SummedQuantity = grouping.Sum(x => (dynamic)useThisForecast.GetValue(x));
请注意,
GetValue
返回一个您可能需要强制转换的
对象-我作弊并使用了
dynamic
,因为我不知道属性的类型

此外,如果您可能正在处理字段或属性,则
MemberInfo
上的一些扩展方法可能会有所帮助:

public static object GetValue(this MemberInfo member, object srcObject) {
    switch (member) {
        case FieldInfo mfi:
            return mfi.GetValue(srcObject);
        case PropertyInfo mpi:
            return mpi.GetValue(srcObject);
        default:
            throw new ArgumentException("MemberInfo must be of type FieldInfo or PropertyInfo", nameof(member));
    }
}

public static Type GetMemberType(this MemberInfo member) {
    switch (member) {
        case FieldInfo mfi:
            return mfi.FieldType;
        case PropertyInfo mpi:
            return mpi.PropertyType;
        case EventInfo mei:
            return mei.EventHandlerType;
        default:
            throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", nameof(member));
    }
}

这是普通Linq(又名Linq To Objects),还是Linq To Something?@nvoight据我所知,这是普通Linq,我正在从结果集中创建一个新对象。当然有一种方法可以将数据读入对象中的
预测集
,并避免这种欺骗?它可以按照您所描述的那样完成,但是非常混乱和缓慢。@Rhumborl数据源是公司使用的excel表,我使用SSIS包和EF将其读入数据库以生成模型。数据是以这种方式从源代码构建的。从长远来看,基于某人的Excel技能设计软件不会让你成为一名快乐的程序员。执行导入数据所需的操作,但将其导入到一个更通用的数据结构中,在该结构中,您不需要像这样提取数据。一年应该是一行,而不是一列。天知道明年电子表格会是什么样子。谢谢!我不知道我可以用这种方式使用该物业,但我几乎不需要改变它。这些扩展方法也很有用,所以我不需要通过对象的“名称”来访问它。