我想从表中只选择两列并将其放在列表中,而不是放入字符串string[,]
的二维数组中。我在这做什么:
string[,] array = _table.Where(x => x.IsDeleted == false)
.Select(y => new string[,] {{y.Name, y.Street}});
现在我不知道如何执行它。如果我.ToArray()
我将获得string[][,]
。任何人都知道如何使用LINQ解决它,而不使用循环?
答案 0 :(得分:2)
string[,]
无法作为LINQ查询的输出。
作为替代方案,你可以尝试这样的事情: -
string[][] array = _table.Where(x => x.IsDeleted == false).Select(y => new[] {y.Name, y.Streete}).ToArray();
OR
var array =_table.Select(str=>str.Where(x => x.IsDeleted == false)
.Select(y => new[] {y.Name, y.Street})
.ToArray())
.ToArray();
答案 1 :(得分:1)
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 });