我有一个MyClass的集合,我想用LINQ来查询获取不同的值,然后得到一个Dictionary
var desiredResults = new Dictionary(StringComparer.OrdinalIgnoreCase); var queryResults = (from MyClass mc in myClassCollection orderby bp.SomePropToSortOn select new KeyValuePair (mc.KeyProp, mc.ValueProp)).Distinct(); foreach (var item in queryResults) { desiredResults.Add(item.Key.ToString(), item.Value.ToString()); }
Mehrdad Afsh.. 360
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);
leppie.. 17
查看ToLookup
和/或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);
查看ToLookup
和/或ToDictionary
扩展方法.