0

If I have two lists:

List<MyModel> list1;
List<MyModel> list2;

How do I create a list3 with all items from list2 that are not present in list1. I want to compare the items from each list by the property string list1.Name and list2.Name.

Note that list3 shouldn't contain any items from list1.

The purpose is that list1 is the original list, which I wants to update with items from list2, by adding each item from list3 to my original list1. I just don't want any duplicates after the update.

Allan
  • 3
  • 2
  • Did you see this: https://stackoverflow.com/questions/3944803/use-linq-to-get-items-in-one-list-that-are-not-in-another-list. Seems exactly what you need. – MakePeaceGreatAgain Feb 17 '19 at 18:05
  • Provided your Lists are of the same type. You can try `var third=list2.Except(list1);` This should produce items that are in `list2` but not in `list1`. – bolkay Feb 17 '19 at 18:15
  • I tried both with 2 if-statements and with 2 foreach-statements, the first didn't work, and the second made a lot of duplicates. I think I will try out the answer from HimBomBeere, it looks like what i need... Thanks – Allan Feb 17 '19 at 18:28

1 Answers1

0

Seems like your list3 is just a temporary list to store items from list2. Simply use this:

var list3 = list2.Where(x => !list1.Any(y => x.MyProperty == y.MyProperty));

And then add them into list1:

list1.AddRange(list3);

You could however directly update your list1 with a simple loop.

foreach(var e in list2)
{
    if(!list1.Any(x => x.MyProperty == e.MyProperty))
        list1.Add(e);
}

You could also use Except which will perform an equality-check on your items. Thus you have to provide an IEqualityComparer:

var list3 = list2.Except(list1, new MyComparer());

class MyComparer : IEqualityComparer<MyElementType>
{
    public bool Equals(MyElementType x, MyElementType y)
    {
        return x.MyProperty == y.MyProperty;
    }
    public int GetHashCode(MyElementType e)
    {
        return e.MyProperty.GetHashCode();
    }
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
  • I needed it as a list, therefor i added .ToList(); to your first suggestion: var list3 = list2.Where(x => !list1.Any(y => x.MyProperty == y.MyProperty)).ToList(); This worked perfectly. The reason why I needed it in a 3rd list, was that I allready had a method that adds a list to my database. Thank you very much for your help!! – Allan Feb 17 '19 at 18:43