1つのリストを2つのリストに分割するか、n個のリストに分割する方法を紹介します。
1. GetRange() でリストを分離する
List.GetRange(index, count)
は、リストの Index から count 個数だけ要素を取得して新しいリストに返します。
以下のように、1つのリストを2つのリストに分割できます。
GetRange(0, 3)
: Index 0から3つの要素をリストに返すGetRange(3, 4)
: Index 3で4つの要素をリストに返す
using System;
namespace Example {
public class Program {
public static void Main(string[] args) {
List<string> list = new List<string>() {"a", "b", "c", "d", "e", "f", "g"};
List<string> splitList1 = list.GetRange(0, 3);
List<string> splitList2 = list.GetRange(3, 4);
Console.WriteLine(string.Join(", ", splitList1));
Console.WriteLine(string.Join(", ", splitList2));
}
}
}
Output:
a, b, c
d, e, f, g
2. GetRange()でn個のリストに分割する
以下の例で直接実装した SplitList(list, size)
関数は、 list の要素を size 個数で割った新しいリストを返します。
たとえば、次のように長さが7のリストを2つずつ分割すると、長さが2のリストが3つ作成され、長さが1のリストが1つ作成されます。
using System;
namespace Example {
public class Program {
public static List<List<string>> SplitList(List<string> list, int size) {
List<List<string>> result = new List<List<string>>();
for (int i = 0; i < list.Count; i += size) {
result.Add(list.GetRange(i, Math.Min(size, list.Count - i)));
}
return result;
}
public static void Main(string[] args) {
List<string> list = new List<string>() {"a", "b", "c", "d", "e", "f", "g"};
List<List<string>> result = SplitList(list, 2);
// show results
for (int i = 0; i < result.Count; i++) {
List<string> splitList = result.ElementAt(i);
Console.WriteLine(string.Join(", ", splitList));
}
}
}
}
Output:
a, b
c, d
e, f
g
Related Posts
- C# - Dictionaryからkey、valueを取得する
- C# - Dictionary 巡回, foreach, for ループ
- C# - Dictionaryからkey、valueを削除する
- C# - Dictionary.add()でデータを追加する
- C# - Dictionary宣言と初期化
- C# - 文字列をDouble、Floatに変換
- C# - 文字列をリストに変換
- C# - 日付計算、DateTime時間プラス減算
- C# - 日付文字列をDateTimeに変換
- C# - 2つの日付/時刻比較、DateTime.Compare()
- C# - Sleep、数秒間遅らせる
- C# - TimestampをDateTimeオブジェクトに変換する
- C# - 現在時刻を取得する、DateTime
- C# - 文字列リストを文字列に変換
- C# - リストコピー(浅いコピー、深いコピー)
- C# - 2次元リスト宣言と初期化
- C# - リスト宣言と初期化
- C# - リストの長さ、サイズを取得する
- C# - リスト合計、平均計算
- C# - リスト要素を削除する(RemoveAt、RemoveAt、RemoveAll)
- C# - リストから空の文字列、nullを削除する