1

I have a list of string[]:

List<string[]> EIndex;

Eindex list has 4 string[]

INPUT:           {0,John},{1,Mike},{2,John},{3,Tim}
Expected OUTPUT: {0,John},{1,Mike},{3,Tim}

I want to distinct the array based on index number 1 of string[] Like:

List<string[]> DistinctList = Eindex.Distinct(obj => obj[1]).ToList();

any suggestion?

Alex K.
  • 171,639
  • 30
  • 264
  • 288

1 Answers1

0

Distinct takes an IEqualityComparer<T> argument. You can implement a custom comparer to equate your arrays by the item at their second index:

public class SecondIndexComparer : IEqualityComparer<string[]>
{
    public bool Equals(string[] x, string[] y)
    {
        return x[1] == y[1];
    }

    public int GetHashCode(string[] obj)
    {
        return obj[1].GetHashCode();
    }
}

And use it like so:

var distinctList = Eindex.Distinct(new SecondIndexComparer()).ToList();

See a working example here: https://dotnetfiddle.net/cpv1i7

Charles Mager
  • 25,735
  • 2
  • 35
  • 45