首页 > 解决方案 > 过滤重复行

问题描述

我这里有一段代码:

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);
    }
});

我想删除注释“//过滤出具有相同 Col1/Col2 组合的行”下的代码,并以某种方式将此功能添加到注释上方的我的 LINQ 语句中

标签: c#.netlinq

解决方案


这应该很适合你:

var dbTableList =
    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
        })
        .GroupBy(x => new
        {
            x.Col1,
            x.Col2
        })
        .SelectMany(xs => xs.Take(1))
        .ToList();

完成这项工作的关键是GroupBy//组合SelectManyTake(1)


推荐阅读