LINQ:Select 除第一项外的所有组
LINQ: Select all from each group except the first item
很容易select每组第一名:
var firstOfEachGroup = dbContext.Measurements
.OrderByDescending(m => m.MeasurementId)
.GroupBy(m => new { m.SomeColumn })
.Where(g => g.Count() > 1)
.Select(g => g.First());
但是...
问题:我如何select每个组中除了第一项以外的所有项?
var everythingButFirstOfEachGroup = dbContext.Measurements
.OrderByDescending(m => m.MeasurementId)
.GroupBy(m => new { m.SomeColumn })
.Where(g => g.Count() > 1)
.Select( ...? );
附加信息:
我的真正目标是删除除最后一个之外的所有重复项(以批量方式,即:不使用内存中的 foreach),所以在上一个查询之后我想使用 RemoveRange
:
dbContext.Measurements.RemoveRange(everythingButFirstOfEachGroup);
所以,如果我的问题没有意义,这个信息可能会派上用场。
使用Skip(1)
跳过第一条记录,select 跳过其余记录。
类似于:
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));
如果您不需要扁平化集合,请将代码段中的 SelectMany
替换为 Select
。
IGrouping<K, V>
实施 IEnumerable<V>
;您只需要跳过 select 子句以将其应用于每个组:
.Select(g => g.Skip(1))
您始终可以使用 .Distinct() 来删除重复项;大概排序或反向排序然后应用 .distinct() 会给你你想要的。
很容易select每组第一名:
var firstOfEachGroup = dbContext.Measurements
.OrderByDescending(m => m.MeasurementId)
.GroupBy(m => new { m.SomeColumn })
.Where(g => g.Count() > 1)
.Select(g => g.First());
但是...
问题:我如何select每个组中除了第一项以外的所有项?
var everythingButFirstOfEachGroup = dbContext.Measurements
.OrderByDescending(m => m.MeasurementId)
.GroupBy(m => new { m.SomeColumn })
.Where(g => g.Count() > 1)
.Select( ...? );
附加信息:
我的真正目标是删除除最后一个之外的所有重复项(以批量方式,即:不使用内存中的 foreach),所以在上一个查询之后我想使用 RemoveRange
:
dbContext.Measurements.RemoveRange(everythingButFirstOfEachGroup);
所以,如果我的问题没有意义,这个信息可能会派上用场。
使用Skip(1)
跳过第一条记录,select 跳过其余记录。
类似于:
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));
如果您不需要扁平化集合,请将代码段中的 SelectMany
替换为 Select
。
IGrouping<K, V>
实施 IEnumerable<V>
;您只需要跳过 select 子句以将其应用于每个组:
.Select(g => g.Skip(1))
您始终可以使用 .Distinct() 来删除重复项;大概排序或反向排序然后应用 .distinct() 会给你你想要的。