remove distinct items
how to remove di开发者_运维知识库stinct items in list from another list in c# ?
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.
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);
}
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.
精彩评论