本文介绍了如何转换数据库成果转化为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想借此从表中只有两列,并把它不在列表中,但成字符串的二维数组字符串[,] 。在这里,我做的:

I want to take only two columns from the table and put it not in the list, but into 2D array of strings string[,]. Here what I do:

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

现在我不知道如何来执行它。如果我做 .ToArray()我会得到的String [] [,] 。任何人都知道如何使用LINQ解决它,而无需使用一个循环?

And now I don't know how to execute it. If I do .ToArray() I'll get string[][,]. Anybody knows how to solve it with LINQ, without using a loop?

推荐答案

有没有在LINQ可以让你创建多维数组。但是,你可以创建自己的扩展方法将返回 TResult [,]

There is nothing in LINQ that let you create multidimentional array. However, you can create your own extension method which will return 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 [] [] ,然后再利用循环将其改写成多维数组。

But as you can see, it still gets all result into jagged array TResult[][] first, and then use loops to rewrite it into multidimentional array.

用法示例:

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

这篇关于如何转换数据库成果转化为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:41