Add Range of items to list without duplication

AyaZoghby picture AyaZoghby · Jan 12, 2013 · Viewed 43.9k times · Source

I have a List of List of Strings, and I need to use the AddRange() Function to add set of items to it, but never duplicate items.

I used the following code :

List<List<string>> eList = new List<List<string>>();
List<List<string>> mergedList = new List<List<string>>(); 

//
// some code here
//

mergedList.AddRange(eList.Where(x => !mergedList.Contains(x)).ToList());

However it does not work.

All Duplicated items are added, so how could I solve that?

Answer

I4V picture I4V · Jan 12, 2013

A)

If what you mean from duplicate is both lists contain the same elements int the same order, then

List<List<string>> eList = new List<List<string>>();
eList.Add(new List<string>() { "a", "b" });
eList.Add(new List<string>() { "a", "c" });
eList.Add(new List<string>() { "a", "b" });


var mergedList = eList.Distinct(new ListComparer()).ToList();

public class ListComparer : IEqualityComparer<List<string>>
{
    public bool Equals(List<string> x, List<string> y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<string> obj)
    {
        return obj.Take(5).Aggregate(23,(sum,s)=> sum ^= s.GetHashCode());
    }
}

B)

If the order of elements in the list is not important, then

List<List<string>> eList = new List<List<string>>();
eList.Add(new List<string>() { "a", "b" }); <--
eList.Add(new List<string>() { "a", "c" });
eList.Add(new List<string>() { "b", "a" }); <--

var mergedList = eList.Select(x => new HashSet<string>(x))
                      .Distinct(HashSet<string>.CreateSetComparer()).ToList();