LINQ查询返回一个Dictionary <string,string>
我有一个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());
}
直接使用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);
查看ToLookup
和/或ToDictionary
扩展方法。
上一篇: LINQ query to return a Dictionary<string, string>
下一篇: How do I use Linq to obtain a unique list of properties from a list of objects?