Help us understand the problem. What is going on with this article?

対象のリストからフィルタに含まれない要素を除外する (C#)

前提

  • Linqは使いたくないものとします。
  • staticクラス内で定義しない(拡張メソッドにしない)場合は、第1引数のthisを取ってください。

やりたいこと

  • 対象が{ B, C, D, E, F }で、フィルターが{ A, B, D, E, G, H }のとき、{ B, D, E }を得たいです。

コード

対象のリストを書き替える場合

TargetList.RemoveAll (t => !FilterList.Contains (t));

新しいリストを返す場合

var result = TargetList.FindAll (t => FilterList.Contains (t));

ダメなやり方

この方法だと、リストを前から順にスキャンするループ中に要素が削除されてズレるので、スキャンから漏れる要素が生じます。

for (var i = 0; i < TargetList.Count; i++) {
    if (!FilterList.Contains (target [i])) { TargetList.RemoveAt (i); }
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away