Thursday, 15 January 2015

c# - Remove IList items from IList items -



c# - Remove IList<int> items from IList<int> items -

this question has reply here:

remove items in 1 ilist<> ilist<> [duplicate] 4 answers

i trying remove list<int> items list<int> items2

list<int> item1 = new list<int> {1,2,3,4,5,6,7,8,9,10}; list<int> item2 = new list<int> {1,2,3,4};

after removing item2 values item1 required result is

item1 = {5,6,7,8,9,10 }

is there direct method or other method remove contents of 1 list of items content of list of items, out using 'for' or 'foreach' ?

something somewhere going have loop. don't have loop in your source code though. do... depends on requirements.

if alter types of variables list<int> utilize list<t>.removeall:

item1.removeall(x => item2.contains(x));

or utilize linq, if you're happy item1 changing value refer different list:

item1 = item1.except(item2).tolist();

note above also create item1 set of distinct values - if have duplicates, removed (even if they're not in item2).

an alternative without duplicate-removing aspect:

item1 = item1.where(x => !item2.contains(x)).tolist();

or create perform improve if item2 large:

var item2set = new hashset<int>(item2); item1 = item1.where(x => !item2set.contains(x)).tolist();

c# list

No comments:

Post a Comment