简体   繁体   English

列出到多维数组的一维

[英]List to single dimension of multidimensional array

Is it possible without looping (ie 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或foreach以及使用某些LINQ或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, ie 这样整数1到5将填充列3,即

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

Many Thanks. 非常感谢。

You can't do it with the standard Linq operators (at least not easily), but you can create a dedicated extension method: 您不能使用标准的Linq运算符来做到这一点(至少不容易),但是可以创建一个专用的扩展方法:

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. 甚至Linq运算符也在内部使用循环。

List<T> has a ForEach method that you can use -- it's not LINQ, but it will get you what you want: List <T>有一个可以使用的ForEach方法-它不是LINQ,但是它将为您提供所需的东西:


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

This is a weird requirement, I'd be curious what your trying to accomplish with it. 这是一个不可思议的要求,我很好奇您试图用它来完成什么。

(LinqPad example) (LinqPad示例)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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