1

我只想从表中取出两列,而不是将其放入列表中,而是放入 2D array of stringsstring[,]中。我在这里做什么:

string[,] array = _table.Where(x => x.IsDeleted == false)
     .Select(y => new string[,] {{y.Name, y.Street}});

现在我不知道如何执行它。如果我这样做,.ToArray()我会得到string[][,]. 有人知道如何在不使用循环的情况下使用 LINQ 解决它吗?

4

2 回答 2

2

string[,]无法作为 LINQ 查询的输出获得。

作为替代方案,您可以尝试这样的事情:-

 string[][] array = _table.Where(x => x.IsDeleted == false).Select(y => new[] {y.Name, y.Streete}).ToArray();

或者

var array =_table.Select(str=>str.Where(x => x.IsDeleted == false)
        .Select(y => new[] {y.Name, y.Street})
        .ToArray())
    .ToArray();
于 2013-08-17T12:50:16.063 回答
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 });
于 2013-08-17T13:23:12.043 回答