开发者

find distinct element in list in C#

I have a list

   List<string[]> finalResult = new List<string[]>();

after it contains

 finalResult[0][0]='After'
 finalResult[1][0]='Before'
 finalResult[2][0]='Before'

I want to find number of distinct elements in this list. I am using

int noElements=  finalResult.Distinct<string[]>().ToList().Count;

But it is showing no开发者_如何学JAVAElements=3. Any idea why?


The reason you get all three is that the list contains three different string arrays. Two of them happen to have the same content, but it's still two different arrays.

A quick attempt to solve it could look like this:

First create an IEqualityComparer<string[]>:

public class StringArrayComparer : IEqualityComparer<string[]>
{

    public bool Equals(string[] x, string[] y)
    {
        if (x==y)
        {
            return true;
        }

        if (x== null || y == null)
        {
            return false;
        }

        return x.Except(y).Count() == 0;
    }

    public int GetHashCode(string[] obj)
    {
        // there may be better implementations of GetHashCode
        int sum = obj.Sum(s => s.GetHashCode());
        return sum.GetHashCode();
    }
}

...then use that comparer when calling Distinct:

var comparer = new StringArrayComparer();
int distinctCount = finalResult.Distinct(new StringArrayComparer()).Count();


Why do you have a 2-dimensional array here, when you only use one of the dimensions?

Your code should look like this:

 List<string> finalResult = new List<string>();

finalResult[0]="After";
finalResult[1]="Before";
finalResult[2]="Before";

Then you should get the wanted result

int noElements=  finalResult.Distinct().Count(); //returns 2


you need to pass in an IEqualityComparer object that instructs the distinct method on how to compare string arrays.

Define the comparer:

public class MyComparer : IEqualityComparer<string[]>
{
  public bool Equals(string[] a, string[] b)
  {
    if (a.Length != b.Length ) return false;

    for (int i  = 0; i < a.Length;i++)
    {
       if (a[i] != b[i])
         return false;
    }

    return true;
  }



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

call with:

finalResult.Distinct(new MyComparer()).Count();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜