简体   繁体   中英

How to convert db results into 2D array

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

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?

string[,] is not possible to get as an output of LINQ query.

As an alternative you can try something like this:-

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

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

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.

Usage example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM