Rio*_*Rio 2 c# dictionary list anonymous-types
简短的故事:我想将列表/字典转换为匿名对象
基本上我以前拥有的是:
var model = from item in IEnumerable<Item>
select new
{
name = item.Name
value = item.Value
}
Run Code Online (Sandbox Code Playgroud)
如果我有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 };
Run Code Online (Sandbox Code Playgroud)
对于Dictionary<TKey,TValue>你可以简单地这样做:
var model = from item in yourDictionary
select new {
name = item.Key
value = item.Value
};
Run Code Online (Sandbox Code Playgroud)
这工作,因为Dictionary<TKey,TValue>工具IEnumerable<KeyValuePair<TKey,TValue>>所以在第二个表达式item将分型为KeyValuePair<TKey,TValue>这意味着你可以使用项目的新类型item.Key和item.Value.
| 归档时间: |
|
| 查看次数: |
4667 次 |
| 最近记录: |