tags:

views:

66

answers:

3

how to remove distinct items in list from another list in c# ?

A: 
var distinctItems = items.Distinct();

Not quite what you asked for, but it's a lot easier to make a new list by copying items that you want to keep, than trying to edit the original list.

If you want to control what constitutes "equality" for your list items, then call the overload that accepts an instance of IEqualityComparer<T>.

See MSDN.

Christian Hayter
+2  A: 

You could use Except like so:

  var result = list2.Except(list1).ToList();

So an example would be:

List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
List<int> b = new List<int>() { 1, 2, 3, 4 };
List<int> c = a.Except(b).ToList();

Where List C would only have the value 5 in it.

Matt Dearing
thanks that is what I mean
salamonti
+1  A: 

Not as elegant as using Except (which I never knew existed)... but this works:

    List<string> listA = new List<string>();
    List<string> listB = new List<string>();

    listA.Add("A");
    listA.Add("B");
    listA.Add("C");
    listA.Add("D");

    listB.Add("B");
    listB.Add("D");

    for (int i = listA.Count - 1; i >= 0; --i)
    {
        int matchingIndex = listB.LastIndexOf(listA[i]);

        if (matchingIndex != -1)
            listB.RemoveAt(matchingIndex);
    }
beaudetious
OK, I tested the Except method and it's definitely more elegant: List<string> listC = listA.Except(listB).ToList();This will create a third list with only the items in listA that are not found in listB.
beaudetious
Wish they'd allow formatting in the comments! :)
beaudetious