C# 使用 LINQ 选择 Dictionary<T1, T2>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/617283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select a Dictionary<T1, T2> with LINQ
提问by Rich
I have used the "select" keyword and extension method to return an IEnumerable<T>
with LINQ, but I have a need to return a generic Dictionary<T1, T2>
and can't figure it out. The example I learned this from used something in a form similar to the following:
我已经使用“select”关键字和扩展方法来返回一个IEnumerable<T>
with LINQ,但是我需要返回一个泛型Dictionary<T1, T2>
并且无法弄清楚。我从中学到的示例使用了类似于以下形式的内容:
IEnumerable<T> coll = from x in y
select new SomeClass{ prop1 = value1, prop2 = value2 };
I've also done the same thing with extension methods. I assumed that since the items in a Dictionary<T1, T2>
can be iterated as KeyValuePair<T1, T2>
that I could just replace "SomeClass" in the above example with "new KeyValuePair<T1, T2> { ...
", but that didn't work (Key and Value were marked as readonly, so I could not compile this code).
我也对扩展方法做了同样的事情。我假设因为 a 中的项目 Dictionary<T1, T2>
可以迭代,KeyValuePair<T1, T2>
因为我可以用“”替换上面例子中的“SomeClass new KeyValuePair<T1, T2> { ...
”,但这不起作用(键和值被标记为只读,所以我无法编译这段代码)。
Is this possible, or do I need to do this in multiple steps?
这是可能的,还是我需要分多个步骤执行此操作?
Thanks.
谢谢。
采纳答案by Quintin Robinson
The extensions methods also provide a ToDictionaryextension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.
扩展方法还提供了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);
Then objectDictionary[1]
Would contain the value "Hello"
然后objectDictionary[1]
将包含值“Hello”
回答by albertein
var dictionary = (from x in y
select new SomeClass
{
prop1 = value1,
prop2 = value2
}
).ToDictionary(item => item.prop1);
That's assuming that SomeClass.prop1
is the desired Key
for the dictionary.
那是假设这SomeClass.prop1
是Key
字典所需的。
回答by Antoine Meltzheim
A collection of KeyValuePair
is even more explicit, and executes very well.
的集合KeyValuePair
更加明确,并且执行得非常好。
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);