沒有什麼在LINQ可以讓你創建多維數組。但是,您可以創建自己的擴展方法將返回TResult[,]
:
public static class Enumerable
{
public static TResult[,] ToRectangularArray<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult[]> selector)
{
// check if source is null
if (source == null)
throw new ArgumentNullException("source");
// load all items from source and pass it through selector delegate
var items = source.Select(x => selector(x)).ToArray();
// check if we have any items to insert into rectangular array
if (items.Length == 0)
return new TResult[0, 0];
// create rectangular array
var width = items[0].Length;
var result = new TResult[items.Length, width];
TResult[] item;
for (int i = 0; i < items.Length; i++)
{
item = items[i];
// item has different width then first element
if (item.Length != width)
throw new ArgumentException("TResult[] returned by selector has to have the same length for all source collection items.", "selector");
for (int j = 0; j < width; j++)
result[i, j] = item[j];
}
return result;
}
}
但正如你所看到的,但它仍然得到所有結果成鋸齒狀排列TResult[][]
,然後再利用循環將其改寫成多維數組。
用例:
string[,] array = _table.Where(x => x.IsDeleted == false)
.ToRectangularArray(x => new string[] { x.Name, x.Street });
你不能得到'字符串[,]'作爲LINQ查詢的輸出。 – MarcinJuraszek