给定字符串:“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();
}
如果列表不能被三整除,这种方法也适用。
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);
}