4
1

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 5 years have passed since last update.

C# List<T>特定の要素を先頭へ移動させる

Last updated at Posted at 2018-09-11

List内に一致する要素があれば、その要素だけを先頭へ移動させて、
その他の要素は元のままになるように並べ替える方法です。

#Remove()

Remove()を実行して、一致する要素があったかどうかを事後確認し、
要素があった場合はindex0へInsert()します。

var list = new List<string>() { "A", "B", "C", "D", "E" };
if (list.Remove("C"))
{
    list.Insert(0, "C");
}
foreach (var item in list) Console.WriteLine(item);

#IndexOf()

IndexOf() を実行して、一致する要素があればRemoveAt()で削除し、
その後index0へInsert()します。
返り値が0の場合は既に希望の並びになっているので何もしません。

var list = new List<string>() { "A", "B", "C", "D", "E" };
if (list.IndexOf("C") > 0)
{
    list.RemoveAt(list.IndexOf("C"));
    list.Insert(0, "C");
}
foreach (var item in list) Console.WriteLine(item);

#結果は
C
A
B
D
E
となります。

4
1
1

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
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?