简短的故事:我想将列表/字典转换为匿名对象

基本上我以前是:

var model = from item in IEnumerable<Item>
   select new
     {
     name = item.Name
     value = item.Value
     }


等等
如果列表或字典中有name, item.Name,如何创建相同的匿名对象model

编辑:澄清:
如果字典包含[name, item.Name][value, item.Value]作为键值对,那么在不假定您既不知道model也不name的情况下,如何创建value

最佳答案

由于List<T>实现IEnumerable<T>,因此您现有的代码应以完全相同的方式工作:

var model = from item in yourList
            select new { name = item.Name };


对于Dictionary<TKey,TValue>,您可以简单地执行以下操作:

var model = from item in yourDictionary
            select new {
                name = item.Key
                value = item.Value
            };


这是可行的,因为Dictionary<TKey,TValue>实现了IEnumerable<KeyValuePair<TKey,TValue>>,因此在第二个表达式中,item将被键入为KeyValuePair<TKey,TValue>,这意味着您可以使用item.Keyitem.Value投影新类型。

10-07 19:04
查看更多