【问题标题】:How to convert db results into 2D array如何将数据库结果转换为二维数组
【发布时间】:2013-08-17 12:45:59
【问题描述】:

我只想从表中取出两列,而不是将其放入列表中,而是放入二维字符串数组string[,]。这是我的工作:

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

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

【问题讨论】:

  • 您无法将string[,] 作为 LINQ 查询的输出。

标签: c# arrays linq list


【解决方案1】:

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();

【讨论】:

  • 他想要string[,],而不是string[][]
  • string[,] 是一个多维数组,OP 提到将其转换为二维数组。(如果我错了,请纠正我!!)
  • 他指定了他想要的string[,]。 string[][] 是锯齿状的字符串数组。
  • @MarcinJuraszek:- 刚刚更新了我的答案。希望这有效!!!!如果我完全错了,请纠正我:)
  • @RahulTripathi 还是 string[][].
【解决方案2】:

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 });

【讨论】:

  • @Sayse 我不知道为什么这被否决了,但我知道== false 是来自问题的原始查询的一部分,这就是为什么我没有将其更改为!IsDeleted。跨度>
猜你喜欢
  • 2013-10-12
  • 2011-02-17
  • 2011-07-05
  • 2019-07-09
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多