使用反射拆分对象

时间:2019-03-14 21:34:37

标签: c# linq reflection

我具有以下对象类型

public class TestClass
{
    public string Property_1;
    public string Property_2;
    public int property_3;
    public DateTime TimeStame;
}

我的数据源正在返回这些列表

List<TestClass> DataResponse;

我正在尝试对所有数据进行分组,以便按日期对所有Property_1进行分组,而对所有其他属性也是如此。所以本质上我最终得到了:

Dictionary<DateTime, List<Property_1>>
Dictionary<DateTime, List<Property_2>>
Dictionary<DateTime, List<Property_3>>

我可以使用以下方法迭代属性:

foreach (var property in typeof(TestClass).GetProperties())
{

}

但是我不确定如何使用linq来填充字典。

任何帮助都会很棒! 谢谢

2 个答案:

答案 0 :(得分:0)

原始

反射似乎过大。您可以只使用ToDictionary

var result1 = DataResponse.ToDictionary(x => x.Property_1);
var result2 = DataResponse.ToDictionary(x => x.Property_2);
var result3 = DataResponse.ToDictionary(x => x.Property_3);

如果您需要更多的详细信息,请使用GroupBy

如果您想无时间量化日期,可以使用x.Property_3.Date


已更新

无论如何,您应该只使用GroupBy

var result1 = DataResponse.GroupBy(x => x.Property_1);
var result2 = DataResponse.GroupBy(x => x.Property_2);
var result3 = DataResponse.GroupBy(x => x.Property_3);

...

foreach(var result in result1)
{
    // do something with your groups
}

答案 1 :(得分:0)

我想这样的事情应该可以解决

var prop1 = new Dictionary<DateTime, List<string>>();
var prop2 = new Dictionary<DateTime, List<string>>();
var prop3 = new Dictionary<DateTime, List<int>>();

foreach (var grouped in list.GroupBy(l => l.TimeStamp))
{
    prop1.Add(grouped.Key, grouped.Select(i => i.Property_1).ToList());
    prop2.Add(grouped.Key, grouped.Select(i => i.Property_2).ToList());
    prop3.Add(grouped.Key, grouped.Select(i => i.Property_3).ToList());
}