简体   繁体   English

LINQ 查询返回字典<string, string></string,>

[英]LINQ query to return a Dictionary<string, string>

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.我有一个 MyClass 的集合,我想使用 LINQ 进行查询以获取不同的值,并返回 Dictionary<string, string> 作为结果,但我不知道如何比我更简单在下面做。 What would some cleaner code be that I can use to get the Dictionary<string, string> as my result?我可以使用哪些更简洁的代码来获取 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());
}

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);

Look at the ToLookup and/or ToDictionary extension methods.查看ToLookup和/或ToDictionary扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM