c# - 过滤重复行

标签 c# .net linq

我这里有一段代码:

var grouped = nonGrouped.GroupBy(x => new
{
    x.Id,
    x.Col1,
    x.Col2
}).Select(x => new MyDbTable
{
    Id = x.Key.Id,
    VALUE = x.Sum(y => y.Value),
    Col1 = x.Key.Col1,
    Col2 = x.Key.Col2
}).ToList();

//Filter out rows with the same Col1/Col2 combination
var dbTableList = new List<MyDbTable>();
grouped.ForEach(x =>
{
    if (!dbTableList.Any(a => a.Col1 == x.Col2 && a.Col2 == x.Col1))
    {
        dbTableList.Add(x);
    }
});

我想删除注释“//Filter out rows with the same Col1/Col2 combination”下的代码,并以某种方式将此功能添加到注释上方的 LINQ 语句中

最佳答案

我认为您正在寻找 grouped 列表的自定义不同值

class MyDbTableComparer : IEqualityComparer<MyDbTable>
{
    public bool Equals(MyDbTable x, MyDbTable y)
    {
        if (x.Col1 == y.Col2 && x.Col2 == y.Col1) return true;
        return false;
    }
}

然后,将上面的语句更改为:

.Select(x => new MyDbTable
{
    Id = x.Key.Id,
    VALUE = x.Sum(y => y.Value),
    Col1 = x.Key.Col1,
    Col2 = x.Key.Col2
}).ToList().Distinct(new MyDbTableComparer());

但我不知道如果在 ToList() 之前使用 Distinct() 是否会正常工作

关于c# - 过滤重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50759062/

相关文章:

c# - Interlocked.CompareExchange 如果不相等?

c# - 按下箭头键时跳转组合框

c# - 回调中的 WCF 服务超时

c# - 如何将此字符串转换为普通字符串以便将其放入 HTML 文档中?

asp.net - 如何在 LINQ 中使用 IN 运算符

c# - Enumerable.Single 的错误执行?

c# - 获取 List<T> 的现有实例

.net - 从某个线程调用方法时"Unable to evaluate expression because the code is optimized"

.net - XSLT:禁用整个文档中的输出转义

c# - 如何用简单的英语解释这个 lambda 表达式?