1

items2List<int>からアイテムを削除しようとしていますList<int>

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};

item1からitem2の値を削除した後、必要な結果は次のようになります。

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

'for'または'foreach'を使用せずに、あるリストのアイテムのコンテンツを別のアイテムのリストのコンテンツから削除する直接的な方法または他の方法はありますか?

4

1 に答える 1

10

Something somewhere is going to have to loop. You don't have to loop in your source code though. As to what you do... that depends on your requirements.

If you change the types of your variables to List<int> you could use List<T>.RemoveAll:

item1.RemoveAll(x => item2.Contains(x));

Or you could just use LINQ, if you're happy with item1 changing value to refer to a different list:

item1 = item1.Except(item2).ToList();

Note that the above will also make item1 a set of distinct values - if you have any duplicates, they will be removed (even if they're not in item2).

An alternative without the duplicate-removing aspect:

item1 = item1.Where(x => !item2.Contains(x)).ToList();

Or to make it perform better if item2 is large:

var item2Set = new HashSet<int>(item2);
item1 = item1.Where(x => !item2Set.Contains(x)).ToList();
于 2013-02-18T17:55:11.933 に答える