C#list pool /删除重复项

时间:2017-05-12 16:15:49

标签: c# asp.net list

我有一个如下所示的列表:

Id: 1
Line1: Microsoft
Line2: Windows
Line3: Server
Line4: null
Line5: null

Id: 2
Line1: Microsoft
Line2: Windows
Line3: Server
Line4: null
Line5: null

Id: 3
Line1: Microsoft
Line2: Windows
Line3: Server
Line4: Development
Line5: null

现在我想汇集/删除所有重复项(Id 1和2)。 这怎么可能?

我试过这样的事情:

result = result.DistinctBy(x => x.Line3).ToList();

但是它也会删除不正确的Id 3。

预期输出:

Id: 2              // can also be 1, doesn't matter
Line1: Microsoft
Line2: Windows
Line3: Server
Line4: null
Line5: null

Id: 3
Line1: Microsoft
Line2: Windows
Line3: Server
Line4: Development
Line5: null

2 个答案:

答案 0 :(得分:1)

一种简单的方法是创建Tuple作为分组对象。

result = result.GroupBy(r => Tuple.Create(r.Line1, r.Line2, r.Line3, r.Line4, r.Line5))
               .Select(g => g.First())
               .ToList();

我没有DistinctBy,但这应该有效:

result = result.DistinctBy(r => Tuple.Create(r.Line1, r.Line2, r.Line3, r.Line4, r.Line5))
               .ToList();

答案 1 :(得分:0)

你在DistinctBy的正确轨道上你只需要创建一个包含你关心的所有字段的匿名类型

result = result.DistinctBy(x => new {x.Line1, x.Line2, x.Line3, x.Line4, x.Line5}).ToList();
相关问题