与えられた文字列: "a"、 "b"、 "c"、 "d"、 "e"、 "f"、 "g"、 "h"、どうすればそのように配置できますか:
-1- -2- -3-
"a" "b" "c"
-1- -2- -3-
"d" "e" "f"
-1- -2- -3-
"g" "h" "df"
1,2,3は列名です。(データテーブル内)
与えられた文字列: "a"、 "b"、 "c"、 "d"、 "e"、 "f"、 "g"、 "h"、どうすればそのように配置できますか:
-1- -2- -3-
"a" "b" "c"
-1- -2- -3-
"d" "e" "f"
-1- -2- -3-
"g" "h" "df"
1,2,3は列名です。(データテーブル内)
以下を使用したLinqアプローチは次のEnumerable.GroupBy
とおりです。
List<string> strings = new List<string>() { "a", "b", "c", "d", "e", "f", "g", "h" };
var trios = strings
.Select((s, i) => new { Str = s, Index = i })
.GroupBy(x => x.Index / 3);
foreach(var trio in trios){
var newRow = table.Rows.Add(); // your DataTable here
newRow.ItemArray = trio.Select(x => x.Str).ToArray();
}
このアプローチは、リストが3で割り切れない場合にも機能します。
foreach (var data in new[] { "a", "b", "c", "d", "e", "f", "g", "h", "df" }.Select((s, i) => new { Value = s, Column = i % 3 + 1 }))
{
Insert(data.Column, data.Value);
}