0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-06-07

前提

  • Linqは使いたくないものとします。

やりたいこと

  • 対象が{ 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); }
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?