Question

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?

Was it helpful?

Solution

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();

OTHER TIPS

Try following LINQ query

mergeList.AddRange( eList.Where (x => mergeList.Where ( y => y.Intersect(x)).Any()));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top