开发者

List to single dimension of multidimensional array

开发者 https://www.devze.com 2023-04-09 05:52 出处:网络
Is it possible without looping (i.e. without using for or foreach and with some LINQ or Array method) to insert the elements of a list into a single dimension of a declared multidimensional array?

Is it possible without looping (i.e. without using for or foreach and with some LINQ or Array method) to insert the elements of a list into a single dimension of a declared multidimensional array?

For example - from list:

List<int> l开发者_运维技巧 = new List<int> { 1, 2, 3, 4, 5 };

To multidimensional array:

int [,] a = new int[5, 3]; //5 rows 3 columns

Such that the integers 1 to 5 populate column 3, i.e.

a[0, 2] = 1;
a[1, 2] = 2;
a[2, 2] = 3;
a[3, 2] = 4;
a[4, 2] = 5;

Many Thanks.


List<T> has a ForEach method that you can use -- it's not LINQ, but it will get you what you want:


List l = new List { 1, 2, 3, 4, 5 }; 
int [,] a = new int[5, 3]; //5 rows 3 columns 

int i = 0;
l.ForEach(item => a[i++, 2] = item);


You can't do it with the standard Linq operators (at least not easily), but you can create a dedicated extension method:

public TSource[,] ToBidimensionalArrayColumn<TSource>(this IEnumerable<TSource> source, int numberOfColumns, int targetColumn)
{
    TSource[] values = source.ToArray();
    TSource[,] result = new TSource[values.Length, numberOfColumns];
    for(int i = 0; i < values.Length; i++)
    {
        result[i, targetColumn] = values[i];
    }
    return result;
}

BTW, there is no way to do it without a loop. Even Linq operators use loops internally.


This is a weird requirement, I'd be curious what your trying to accomplish with it.

(LinqPad example)

void Main()
{
    List<int> l = new List<int> { 1, 2, 3, 4, 5 };
    ToFunkyArray<int>(l, 4,3).Dump();
}

public T[,] ToFunkyArray<T>(IEnumerable<T> items, int width, int targetColumn)
{
    var array = new T[items.Count(),width];
    int count=0;
    items.ToList().ForEach(i=>{array[count,targetColumn]=i;count++;});
    return array;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消