使用Linq来获取在一个字段中具有重复值的最后N行数[英] Using Linq to get the last N number of rows that have duplicated values in a field

本文是小编为大家收集整理的关于使用Linq来获取在一个字段中具有重复值的最后N行数的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

给定一个数据库表,一个列名 C 和一个大于 1 的数字 N,我怎样才能得到一组具有相同值的列 C 至少有 N 行的行?如果存在多个这样的组,我需要获取包含最新条目的组(具有最大 Id 的组).

是否可以使用 LINQ to Entities 做到这一点?

Example:

> Id | Mycolumn
> - - - - - - -  
> 1 | name55555
> 2 | name22
> 3 | name22
> 4 | name22
> 5 | name55555
> 6 | name55555
> 7 | name1

Primary Key: ID
OrderBy: ID
Repeated column: Mycolumn

如果 N = 3 和 C = Mycolumn,那么我们需要获取列 MyColumn 至少重复 3 次的行.

对于上面的示例,它应该返回第 1、5 和 6 行,因为 name55555 的最后一个索引是 6,而 name22 的最后一个索引(也重复 3 次)是 4.

推荐答案

data.Mytable
    .OrderByDescending(m => m.Id)
    .GroupBy(m => m.Mycolumn)
    .FirstOrDefault(group => group.Count() >= N)
    .Take(N)
    .Select(m => m.Id)

本文地址:https://www.itbaoku.cn/post/1556831.html

问题描述

Given a database table, a column name C, and a number N larger than 1, how can I get a group of rows with equal values of column C which has at least N rows? If there exists more than one such group, I need to get the group which contains the newest entry (the one with the largest Id).

Is it possible to do this using LINQ to Entities?

Example:

> Id | Mycolumn
> - - - - - - -  
> 1 | name55555
> 2 | name22
> 3 | name22
> 4 | name22
> 5 | name55555
> 6 | name55555
> 7 | name1

Primary Key: ID
OrderBy: ID
Repeated column: Mycolumn

If N = 3 and C = Mycolumn, then we need to get rows which have the column MyColumn duplicated at least 3 times.

For the example above, it should return rows 1, 5 and 6, because last index of name55555 is 6, and last index of name22 (which is also repeated 3 times) is 4.

推荐答案

data.Mytable
    .OrderByDescending(m => m.Id)
    .GroupBy(m => m.Mycolumn)
    .FirstOrDefault(group => group.Count() >= N)
    .Take(N)
    .Select(m => m.Id)