Listの要素の追加や削除って使っていますか?C#ではListの要素を追加、削除するメソッドがいくつか用意されています。
この記事では、Listの要素の追加、削除について
- Addで要素を追加する
- AddRangeで要素を追加する
- Insertで要素を追加する
- Removeで要素を削除する
- RemoveAtで要素を削除する
- RemoveRangeで要素を削除する
- RemoveAllで要素を削除する
- Clearで要素を削除する
- Listの末尾にListを追加する
- 重複なしで要素を追加する
- foreachで削除する場合の注意点
など基本的な内容から、応用的な内容についても解説していきます。今回はListの要素の追加、削除について、使い方をわかりやすく解説します!
Listに要素を追加する方法
Addで要素を追加する
Listのオブジェクトに要素を追加するには、Addメソッドを使います。
Addメソッドは以下のように定義されています。
public void Add(
T item
)
引数itemには、末尾に追加するオブジェクトを指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic; // 追加
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Osaka, Nagoya]
このサンプルコードでは、Addメソッドを使ってList型のオブジェクトlistに要素を追加しています。
※処理と合わせて「using System.Collections.Generic;」を呼ぶのを忘れないようにしましょう。
AddRangeで要素を追加する
List型のオブジェクトにコレクションを追加するには、AddRangeメソッドを使います。
AddRangeメソッドは以下のように定義されています。
public void AddRange(
IEnumerable<T> collection
)
引数には末尾に追加するコレクションを指定します。
コレクションとは、配列のように多数のオブジェクトをひとかたまりで扱えて、しかも動的に要素数を変えることができます。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
string[] src = {"Tokyo", "Osaka", "Nagoya"};
var list = new List<string>();
list.AddRange(src);
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Osaka, Nagoya]
このサンプルコードでは、AddRangeメソッドを使ってList型のオブジェクトlistに配列srcの要素を追加しています。
Insertで要素を追加する
これまでは末尾に追加する方法についてお伝えしてきました。
末尾以外にも位置を指定して要素を追加したい場合があります。そんな場合にはInsertメソッドを使用します。
Insertメソッドは以下のように定義されています。
public void Insert(
int index,
T item
)
引数Indexでは、挿入する位置を0(ゼロ)から始まる整数値で指定します。引数itemでは、挿入するオブジェクトを指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.Insert(1, "Yokohama");
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Yokohama, Osaka, Nagoya]
このサンプルコードでは、Insertメソッドを使ってList型のオブジェクトlistの先頭から2番目に要素を追加しています。
Listの末尾にListを追加する
Listの末尾にListを追加するには、先ほどお伝えしたAddRangeメソッドを使います。サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list1 = new List<string>();
list1.Add("Tokyo");
list1.Add("Osaka");
list1.Add("Nagoya");
var list2 = new List<string>();
list2.Add("Hiroshima");
list2.Add("Sendai");
list1.AddRange(list2);
Console.WriteLine("[{0}]", string.Join(", ", list1));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Osaka, Nagoya, Hiroshima, Sendai]
このサンプルコードでは、AddRangeメソッドを使って、List型のオブジェクトlist1の末尾にlist2を追加しています。
重複なしで要素を追加する
要素を追加する場合に、重複せずに追加したい場合もあります。そんな場合にはLINQのUnionメソッドを使います。
Unionメソッドは以下のように定義されています。
public static IEnumerable<TSource> Union<TSource>(
this IEnumerable<TSource> first,
IEnumerable<TSource> second,
IEqualityComparer<TSource> comparer
)
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sample
{
class Sample
{
static void Main()
{
var list1 = new List<string>();
list1.Add("Tokyo");
list1.Add("Osaka");
list1.Add("Nagoya");
var list2 = new List<string>();
list2.Add("Tokyo");
list2.Add("Hiroshima");
list2.Add("Sendai");
List<string> list = list1.Union(list2).ToList();
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Osaka, Nagoya, Hiroshima, Sendai]
このサンプルコードでは、Unionメソッドを使ってList型のオブジェクトlist1にlist2の要素が重複しないように追加しています。要素”Tokyo”はどちらの要素にも共通しますが、追加したあとのリストでは重複していません。
ちなみに、UnionメソッドはIEnumerable型のオブジェクトを返しますので、ToListメソッドを使ってList型のオブジェクトに変換しています。
Listの要素を削除する方法
Removeで要素を削除する
要素を削除する方法についてみていきましょう。要素を削除するには、Removeメソッドを使用します。
Removeメソッドは以下のように定義されています。
public bool Remove(
T item
)
引数itemでは、削除する要素を指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.Remove("Osaka");
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Nagoya]
RemoveAtで要素を削除する
要素のインデックス番号で削除する場合は、RemoveAtメソッドを使います。RemoveAtメソッドは以下のように定義されています。
public void RemoveAt(
int index
)
引数Indexでは、削除する要素の0(ゼロ)で始まるインデックス番号を指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.RemoveAt(1);
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo, Nagoya]
RemoveRangeで要素を削除する
範囲を指定して要素を削除するには、RemoveRangeメソッドを使います。RemoveRangeメソッドは以下のように定義されています。
public void RemoveRange(
int index,
int count
)
引数Indexでは、削除する要素の範囲の開始位置をインデックス番号で指定します。引数countでは、削除する要素の数を指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.RemoveRange(1, 2);
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo]
RemoveAllで要素を削除する
条件を満たす要素を削除することもできます。その場合はRemoveAllメソッドを使います。RemoveAllメソッドは以下のように定義されています。
public int RemoveAll(
Predicate<T> match
)
引数matchでは、削除する要素の条件を定義するデリゲートを指定します。デリゲートとはC言語の関数ポインタのようなもので、引数matchには削除する条件を定義したメソッド名やラムダ式を指定します。
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.RemoveAll(judge);
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
static bool judge(string s) {
return s.Contains("a");
}
}
}
実行結果:
[Tokyo]
このサンプルコードでは、RemoveAllメソッドを使って要素の文字列に”a”が含まれていれば、その要素を削除するようにしています。judgeメソッドで文字列に”a”が含まれているかどうかを判定するように定義しています。
これをラムダ式を使って記述すると以下のようになります。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.RemoveAll(s => s.Contains("a"));
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo]
Clearで要素を削除する
要素を全て削除する場合は、Clearメソッドを使います。Clearメソッドは以下のように定義されています。
public void Clear()
サンプルコードで確認しましょう。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
list.Clear();
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[]
foreachで削除する場合の注意点
foreachを使って要素に1個ずつアクセスして、ある条件を満たした場合にRemoveメソッドでその要素を削除しようとするとエラーが発生します。注意しましょう。
例えば以下のとおりです。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
foreach(string item in list) {
if(item.Contains("a")) {
list.Remove(item);
}
}
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
![Remove01]()
これは要素を削除することにより、要素を順に列挙する保証ができなくなるためです。対策としては、forループとRemoveAtメソッドを使ってインデックス番号で要素を指定するか、もしくはRemoveAllメソッドを使うようにしましょう。
forループとRemoveAtメソッドを使う例は以下のようになります。
using System;
using System.Collections.Generic;
namespace Sample
{
class Sample
{
static void Main()
{
var list = new List<string>();
list.Add("Tokyo");
list.Add("Osaka");
list.Add("Nagoya");
for(int i = list.Count - 1; i >= 0; i--) {
if(list[i].Contains("a")) {
list.RemoveAt(i);
}
}
Console.WriteLine("[{0}]", string.Join(", ", list));
Console.ReadKey();
}
}
}
実行結果:
[Tokyo]
このサンプルコードでは、forループとRemoveAtメソッドを使って要素を削除しています。ただし、forループでは要素の末尾からアクセスしています。
これは、要素の先頭からアクセスして削除すると複数の要素を削除する場合に削除されない要素が出てくるからです。注意しましょう!
まとめ
ここでは、Listの要素の追加、削除について説明しました。
要素の追加、削除にはいくつかメソッドが用意されています。それぞれ使い方が異なりますので、目的に合わせて使い分けるようにしましょう。foreachとRemoveメソッドを使う場合はエラーが発生しますので注意しましょう。
使いこなすことができるように、この記事を何度も参考にして下さいね!