Linq选择具有来自IGrouping的变量的不同值的多个

问题描述 投票:-1回答:3

我正在尝试使用LINQ,我需要一些lambda表达式的帮助。

我有一个IGrouping<DateTime, Option>Option类有多个变量,如PriceRoot等。

我试图只选择那些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.
}
c# linq
3个回答
0
投票

听起来像你需要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;
}

0
投票
    foreach (var symbol in optvalues.Select(t => r.Root).Distinct())
    { 
       //...
    }

0
投票

所以你只是将Distinct应用于错误的值

IGrouping<DateTime, Option> optvalues;
foreach (var symbol in optvalues.SelectMany(t => t).Select(t => t.Root).Distinct())
{ 
    //
}
© www.soinside.com 2019 - 2024. All rights reserved.