在 c# 4 中将数组分组为每个包含 n 个元素的数组列表的最佳方法是什么。
例如
string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" };
如果我们取n=3,则应分为。
string[] A1 = {"s1", "s2", "s3"};
string[] A2 = {"s4", "s5", "s6"};
string[] A3 = {"s7", "s8"};
使用 LINQ 可能是一种简单的方法?
这将生成一个包含 3 个元素的字符串数组的数组:
int i = 0;
var query = from s in testArray
let num = i++
group s by num / 3 into g
select g.ToArray();
var results = query.ToArray();
我认为没有一个很好的内置方法,但你可以编写如下所示的方法。
public static IEnumerable<IEnumerable<T>> GroupInto<T>(
this IEnumerable<T> source,
int count) {
using ( var e = source.GetEnumerator() ) {
while ( e.MoveNext() ) {
yield return GroupIntoHelper(e, count);
}
}
}
private static IEnumerable<T> GroupIntoHelper<T>(
IEnumerator<T> e,
int count) {
do {
yield return e.Current;
count--;
} while ( count > 0 && e.MoveNext());
}
int size = 3;
var results = testArray.Select((x, i) => new { Key = i / size, Value = x })
.GroupBy(x => x.Key, x => x.Value, (k, g) => g.ToArray())
.ToArray();
如果您不介意结果输入为
IEnumerable<IEnumerable<T>>
而不是 T[][]
那么您可以完全省略 ToArray
调用:
int size = 3;
var results = testArray.Select((x, i) => new { Key = i / size, Value = x })
.GroupBy(x => x.Key, x => x.Value);
如果您实际上正在使用数组而不是一般的 IEnumerables,特别是如果数组非常大,那么此方法是一种非常快速且节省内存的方法。如果您真的只想要一个 LINQ 语句,那么没关系。
private static T[][] SliceArray<T>(T[] source, int maxResultElements)
{
int numberOfArrays = source.Length / maxResultElements;
if (maxResultElements * numberOfArrays < source.Length)
numberOfArrays++;
T[][] target = new T[numberOfArrays][];
for (int index = 0; index < numberOfArrays; index++)
{
int elementsInThisArray = Math.Min(maxResultElements, source.Length - index * maxResultElements);
target[index] = new T[elementsInThisArray];
Array.Copy(source, index * maxResultElements, target[index], 0, elementsInThisArray);
}
return target;
}
您可以使用此扩展
public static class Extension
{
private static IEnumerable<TList> Split<TList, T>(this TList value, int countOfEachPart) where TList : IEnumerable<T>
{
int cnt = value.Count() / countOfEachPart;
List<IEnumerable<T>> result = new List<IEnumerable<T>>();
for (int i = 0; i <= cnt; i++)
{
IEnumerable<T> newPart = value.Skip(i * countOfEachPart).Take(countOfEachPart).ToArray();
if (newPart.Any())
result.Add(newPart);
else
break;
}
return result.Cast<TList>();
}
public static IEnumerable<IDictionary<TKey, TValue>> Split<TKey, TValue>(this IDictionary<TKey, TValue> value, int countOfEachPart)
{
IEnumerable<Dictionary<TKey, TValue>> result = value.ToArray()
.Split(countOfEachPart)
.Select(p => p.ToDictionary(k => k.Key, v => v.Value));
return result;
}
public static IEnumerable<IList<T>> Split<T>(this IList<T> value, int countOfEachPart)
{
return value.Split<IList<T>, T>(countOfEachPart);
}
public static IEnumerable<T[]> Split<T>(this T[] value, int countOfEachPart)
{
return value.Split<T[], T>(countOfEachPart);
}
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> value, int countOfEachPart)
{
return value.Split<IEnumerable<T>, T>(countOfEachPart);
}
}
MoreLinq提供
Batch
扩展方法
在 .NET 6+ 中
string[] testArray = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8" };
testArray.Chunk(3);