简体   繁体   English

LINQ:从第一个项目以外的每个组中选择全部

[英]LINQ: Select all from each group except the first item

It is easy to select the first of each group: 可以轻松选择每组中的第一组:

        var firstOfEachGroup = dbContext.Measurements
            .OrderByDescending(m => m.MeasurementId)
            .GroupBy(m => new { m.SomeColumn })
            .Where(g => g.Count() > 1)
            .Select(g => g.First());

But... 但...
Question : how can I select all from each group except the first item? 问题 :如何从第一个项目以外的每个组中选择所有项目?

        var everythingButFirstOfEachGroup = dbContext.Measurements
            .OrderByDescending(m => m.MeasurementId)
            .GroupBy(m => new { m.SomeColumn })
            .Where(g => g.Count() > 1)
            .Select( ...? );

Additional information: 附加信息:
My real goal is to delete all duplicates except the last (in a bulk way, ie: not using an in-memory foreach), so after the previous query I want to use RemoveRange : 我的真正目标是删除除最后一个之外的所有重复项(以批量方式,即:不使用内存中的foreach),因此在上一个查询之后我想使用RemoveRange

 dbContext.Measurements.RemoveRange(everythingButFirstOfEachGroup);

So, if my question has no sense, this information might be handy. 所以,如果我的问题毫无意义,这些信息可能会很方便。

Use Skip(1) to skip the first record and select the rest. 使用Skip(1)跳过第一条记录并选择其余记录。

Something like: 就像是:

var firstOfEachGroup = dbContext.Measurements
                    .OrderByDescending(m => m.MeasurementId)
                    .GroupBy(m => new { m.SomeColumn })
                    .Where(g => g.Count() > 1)
                    .SelectMany(g => g.OrderByDescending(r => r.SomeColumn).Skip(1));

See: Enumerable.Skip 请参阅: Enumerable.Skip

If you do not need a flattened collection then replace SelectMany with Select in code snippet. 如果您不需要展平的集合,请将SelectMany替换为Select in code snippet。

IGrouping<K, V> implements IEnumerable<V> ; IGrouping<K, V>实现IEnumerable<V> ; you simply need to skip inside the select clause to apply it to each group: 您只需要跳过select子句以将其应用于每个组:

.Select(g => g.Skip(1))

You can always use .Distinct() to remove duplicates; 您始终可以使用.Distinct()删除重复项; presumably sorting or reverse-sorting and then applying .distinct() would give you what you want. 大概是排序或反向排序然后应用.distinct()会给你你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM