0

I have got a list which looks like this:

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

Now I would like to pool / remove all the duplicates (Id 1 and 2). How is this possible?

I tried something like this:

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

But then it would also remove Id 3 which is not correctly.

Expected output:

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
Tom el Safadi
  • 6,164
  • 5
  • 49
  • 102

2 Answers2

1

A simple method is to create a Tuple as the grouping object.

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

I do not have DistinctBy, but this should work:

result = result.DistinctBy(r => Tuple.Create(r.Line1, r.Line2, r.Line3, r.Line4, r.Line5))
               .ToList();
msitt
  • 1,237
  • 12
  • 27
0

You're on the right track with your DistinctBy you just need to create an anonymous type with all the fields you care about

result = result.DistinctBy(x => new {x.Line1, x.Line2, x.Line3, x.Line4, x.Line5}).ToList();
RobPethi
  • 551
  • 9
  • 27