使用LINQ查找重复的行(带有指定列的列表) [英] Use LINQ to find duplicated rows (with list of specified columns)

查看:92
本文介绍了使用LINQ查找重复的行(带有指定列的列表)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码获取3列的重复行:字符串,日期,货币. 我想知道是否有什么通用方法可以在此LINQ中输入动态的列名列表来查找重复的行?

I use the code below to get the duplicated rows for 3 columns: String, Date, Money. I wonder if there is any general method that I can input a dynamic List of column name in this LINQ to find duplicated rows?

DataTable allDuplicates = dt.AsEnumerable()
    .GroupBy(dr => new
    { 
        Field1 = dr.Field<object>("String"), 
        Field2 = dr.Field<object>("Date"), 
        Field3 = dr.Field<object>("Money"), 
    })
    .Where(g => g.Count() > 1)
    .SelectMany(g => g)
    .ToList().CopyToDataTable();
}

推荐答案

如何使用自定义ArrayEqualityComparer<T>类型(例如在这里列出):

How about with a custom ArrayEqualityComparer<T> type (such as the one listed here):

string[] colsToConsider = ...

var allDuplicates = dt.AsEnumerable()
                      .GroupBy(dr => colsToConsider.Select(dr.Field<object>)
                                                   .ToArray(),
                               new ArrayEqualityComparer<object>())       
                      .Where(g => g.Count() > 1)
                      .SelectMany(g => g)
                      .CopyToDataTable();

如果您发现此处隐含地使用数组索引有点黑,您还可以考虑使用Dictionary<TKey, TValue>(和关联的字典比较器).

You can also consider using a Dictionary<TKey, TValue> (and an associated dictionary-comparer) if you find the implicit use of array indices here hackish.

这篇关于使用LINQ查找重复的行(带有指定列的列表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆