C# LINQ 查询返回一个 Dictionary<string, string>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/627867/
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
LINQ query to return a Dictionary<string, string>
提问by Scott Ivey
I have a collection of MyClass that I'd like to query using LINQ to get distinct values, and get back a Dictionary<string, string> as the result, but I can't figure out how I can do it any simpler than I'm doing below. What would some cleaner code be that I can use to get the Dictionary<string, string> as my result?
我有一个 MyClass 的集合,我想使用 LINQ 查询它以获取不同的值,并返回一个 Dictionary<string, string> 作为结果,但我不知道如何比我更简单地做到这一点正在做下面。我可以使用哪些更简洁的代码来获取 Dictionary<string, string> 作为结果?
var desiredResults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var queryResults = (from MyClass mc in myClassCollection
orderby bp.SomePropToSortOn
select new KeyValuePair<string, string>(mc.KeyProp, mc.ValueProp)).Distinct();
foreach (var item in queryResults)
{
desiredResults.Add(item.Key.ToString(), item.Value.ToString());
}
采纳答案by Mehrdad Afshari
Use the ToDictionary
method directly.
ToDictionary
直接使用该方法。
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
回答by leppie
Look at the ToLookup
and/or ToDictionary
extension methods.
查看ToLookup
和/或ToDictionary
扩展方法。