我已经使用“select”关键字和扩展方法通过 LINQ 返回一个 IEnumerable<T>
,但我需要返回一个通用 Dictionary<T1, T2>
,但无法弄清楚。我从中学到的示例使用了类似于以下形式的内容:
IEnumerable<T> coll = from x in y
select new SomeClass{ prop1 = value1, prop2 = value2 };
我也对扩展方法做了同样的事情。我假设由于 Dictionary<T1, T2>
中的项目可以迭代为 KeyValuePair<T1, T2>
,我可以将上面示例中的“SomeClass”替换为“new KeyValuePair<T1, T2> { ...
”,但这不起作用(键和值被标记为只读的,所以我无法编译这段代码)。
这可能吗,还是我需要分多个步骤执行此操作?
谢谢。
扩展方法还提供 ToDictionary 扩展。它使用起来相当简单,一般的用法是为键传递一个 lambda 选择器并将对象作为值,但您可以为键和值都传递一个 lambda 选择器。
class SomeObject
{
public int ID { get; set; }
public string Name { get; set; }
}
SomeObject[] objects = new SomeObject[]
{
new SomeObject { ID = 1, Name = "Hello" },
new SomeObject { ID = 2, Name = "World" }
};
Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
那么 objectDictionary[1]
将包含值“Hello”
更明确的选择是将集合投影到 KeyValuePair
的 IEnumerable,然后将其转换为字典。
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
假设 SomeClass.prop1
是字典所需的 Key
。
.ToDictionary(item => item.prop1, item => item.prop2);
也明确设置值。