在LINQ中选择一个多维数组[重复]

时间:2021-09-28 02:46:36

This question already has an answer here:

这个问题在这里已有答案:

I have a task where I need to translate a DataTable to a two-dimensional array. That's easy enough to do by just looping over the rows and columns (see example below).

我有一个任务,我需要将DataTable转换为二维数组。只需循环遍历行和列就可以轻松完成(参见下面的示例)。

private static string[,] ToArray(DataTable table)
{
    var array = new string[table.Rows.Count,table.Columns.Count];

    for (int i = 0; i < table.Rows.Count; ++i)
        for (int j = 0; j < table.Columns.Count; ++j)
            array[i, j] = table.Rows[i][j].ToString();

    return array;
}

What I'd really like to do is use a select statement in LINQ to generate that 2D array. Unfortunately it looks like there is no way in LINQ to select a multidimensional array. Yes, I'm aware that I can use LINQ to select a jagged array, but that's not what I want.

我真正想做的是在LINQ中使用select语句来生成该2D数组。不幸的是,看起来在LINQ中没有办法选择多维数组。是的,我知道我可以使用LINQ来选择锯齿状阵列,但这不是我想要的。

Is my assumption correct, or is there a way to use LINQ to select a multi-dimensional array?

我的假设是正确的,还是有办法使用LINQ来选择多维数组?

1 个解决方案

#1


15  

I don't think it is possible. My reasoning is that Select and most other LINQ functions require that the collections they work on implement at least IEnumerable<T> for some T:

我不认为这是可能的。我的理由是Select和大多数其他LINQ函数要求它们使用的集合至少为某些T实现IEnumerable

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

A rectangular array doesn't implement IEnumerable<T> for any T so it can't be the return value of a Select function.

矩形数组不会为任何T实现IEnumerable ,因此它不能是Select函数的返回值。

#1


15  

I don't think it is possible. My reasoning is that Select and most other LINQ functions require that the collections they work on implement at least IEnumerable<T> for some T:

我不认为这是可能的。我的理由是Select和大多数其他LINQ函数要求它们使用的集合至少为某些T实现IEnumerable

public static IEnumerable<TResult> Select<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, TResult> selector
)

A rectangular array doesn't implement IEnumerable<T> for any T so it can't be the return value of a Select function.

矩形数组不会为任何T实现IEnumerable ,因此它不能是Select函数的返回值。