动态定义匿名类型的属性
Define dynamic the properties of an anonymous type
我有一个字典,其中有一个键和一个 IEnumerable 值。
var rowsByMonth = dictionaryByMonth.Select(item => new
{
Station = item.Key.DisplayName,
Month1 = item.Value.FirstOrDefault(element => element.ColumnIndex == 0),
Month2 = item.Value.FirstOrDefault(element => element.ColumnIndex == 1),
Month3 = item.Value.FirstOrDefault(element => element.ColumnIndex == 2),
Month4 = item.Value.FirstOrDefault(element => element.ColumnIndex == 3)
});
问题是如何根据不同 ColumnIndex 的数量动态创建属性 Month1、Month2...。也许我可以拥有具有不同 ColumnIndex 的元素。 ColumnIndexes 是可变的。我需要一个具有已定义属性的匿名类型,因为我想将它绑定到 DataGrid
希望我正确理解了你的问题
我认为你需要使用Tuple
因为你需要灵活的数据结构
Link: https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
样本:
var population = Tuple.Create(item.Key.DisplayName, item.Value.FirstOrDefault(element => element.ColumnIndex == 0), etc, etc);
然后可以得到population.Item1
、population.Item2
等
我有一个字典,其中有一个键和一个 IEnumerable 值。
var rowsByMonth = dictionaryByMonth.Select(item => new
{
Station = item.Key.DisplayName,
Month1 = item.Value.FirstOrDefault(element => element.ColumnIndex == 0),
Month2 = item.Value.FirstOrDefault(element => element.ColumnIndex == 1),
Month3 = item.Value.FirstOrDefault(element => element.ColumnIndex == 2),
Month4 = item.Value.FirstOrDefault(element => element.ColumnIndex == 3)
});
问题是如何根据不同 ColumnIndex 的数量动态创建属性 Month1、Month2...。也许我可以拥有具有不同 ColumnIndex 的元素。 ColumnIndexes 是可变的。我需要一个具有已定义属性的匿名类型,因为我想将它绑定到 DataGrid
希望我正确理解了你的问题
我认为你需要使用Tuple
因为你需要灵活的数据结构
Link: https://msdn.microsoft.com/en-us/library/system.tuple(v=vs.110).aspx
样本:
var population = Tuple.Create(item.Key.DisplayName, item.Value.FirstOrDefault(element => element.ColumnIndex == 0), etc, etc);
然后可以得到population.Item1
、population.Item2
等