我正在尝试使用LINQ,我需要一些lambda表达式的帮助。
我有一个IGrouping<DateTime, Option>
。 Option
类有多个变量,如Price
,Root
等。
我试图只选择那些Option
中的foreach
对象具有不同的Root
值,我不知道如何得到它。我试过这样做:
IGrouping<DateTime, Option> optvalues;
foreach (var symbol in optvalues.SelectMany(t => t.Root.Distinct()))
{
//This is returning some random value “85 S” in rootdiff.
}
听起来像你需要DistinctBy
:
foreach (var symbol in optvalues.DistinctBy(opt => opt.Root)) {
}
这是一种扩展方法:
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keyFun) {
// return src.GroupBy(keyFun).Select(g => g.FirstOrDefault()); // to defer execution
var seenKeys = new HashSet<TKey>();
foreach (T e in src)
if (seenKeys.Add(keyFun(e)))
yield return e;
}
foreach (var symbol in optvalues.Select(t => r.Root).Distinct())
{
//...
}
所以你只是将Distinct
应用于错误的值
IGrouping<DateTime, Option> optvalues;
foreach (var symbol in optvalues.SelectMany(t => t).Select(t => t.Root).Distinct())
{
//
}