2

linq group By Id、Order By降順にしてから、各グループの上位5つを選択する方法はありますか? 現在、以下に示すコードがいくつかありますが、使用.Take(5)したところ、グループ化に関係なく上位 5 つが明らかに選択されます。

Items = list.GroupBy(x => x.Id)
            .Select(x => x.OrderByDescending(y => y.Value))
            .Select(y => new Home.SubModels.Item {
                Name= y.FirstOrDefault().Name,
                Value = y.FirstOrDefault().Value,
                Id = y.FirstOrDefault().Id
            })
4

1 に答える 1

3

あなたはほとんどそこにいます。ステートメントTakeでの使用:Select

var items = list.GroupBy(x => x.Id)   
                //For each IGrouping - order nested items and take 5 of them           
                .Select(x => x.OrderByDescending(y => y.Value).Take(5))

これは を返しますIEnumerable<IEnumerable<T>>。平らにしたい場合はSelectSelectMany

于 2016-10-18T21:22:30.900 に答える