我有一个 MyClass 的集合,我想使用 LINQ 查询以获取不同的值,并返回 Dictionary 作为结果,但我不知道如何比我更简单地做到这一点在下面做。我可以使用哪些更简洁的代码来获取 Dictionary 作为我的结果?
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方法。
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);