我有一个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());
}
答案 0 :(得分:351)
直接使用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);
答案 1 :(得分:17)
查看ToLookup
和/或ToDictionary
扩展方法。