DistinctBy 3 Params

163 views Asked by At

I am trying to use C# MoreLinq to try to figure out duplicates.

Here is an example. There is a league, within the league the teams. Each player in the team can play any position.

public sealed class Triad
{ 
    public int Id1 {get;set;}
    public int Id2 {get;set;}
    public int Id3 {get;set;}
}

With this I want to GroupBy

ArrayOfTraids.GroupBy(new { Id1, Id2, Id3}).Select(t => t);

Example

If Id1 = 1, Id2 = 2 and Id3 = 3, in this example we would get 1 Object.

The problem I want to solve is, If Id1 = 2, Id2 = 3, Id3 = 1, I want it ALSO to be apart of the same list, since the int values are still 1,2,3 (regardless of the order, they are still the same values).

I feel this could be very simple but I am unsure.

SOLVED

Ended up doing something like this

ArrayOfTriads.Where(t => t.Id1 < t.Id2 && t.Id2 < t.Id3) 

Which eliminated the repeating. Closed.

1

There are 1 answers

0
MEC On

Your answer:

ArrayOfTriads.Where(t => t.Id1 < t.Id2 && t.Id2 < t.Id3)

Does not work with the following example. It filters out the first two elements instead of selecting one of them:

ArrayOfTraids.Add(new Triad(3, 2, 1));
ArrayOfTraids.Add(new Triad(2, 3, 1));
ArrayOfTraids.Add(new Triad(1, 2, 4));
ArrayOfTraids.Add(new Triad(1, 2, 5));

You get:

Id1 Id2 Id3
1   2   4
1   2   5

I think that you may want to group by the ordered Id's. Here is a way it could be done:

ArrayOfTraids
.GroupBy(m => (string.Join(";", new List<int> { m.Id1, m.Id2, m.Id3 }
.OrderBy(n => n)))).Select(m => m.First());

This produces:

Id1 Id2 Id3
3   2   1
1   2   4
1   2   5