使用C#LINQ编写具有二维列表的函数 [英] Using C# LINQ to write the function with two dimensional List

查看:57
本文介绍了使用C#LINQ编写具有二维列表的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简单起见,我想用C ++语法编写一个返回Z * Y矩阵(Y> Z)的函数:

I want to write a function with returning a Z*Y matrix(Y>Z), in C++ Syntax for simplicity:

double[Z][Y] Function (double[Y] vector){
    for (int i, i<Z, i++){
        for (int j, j<Y, j++){
            double[Z][Y] Tem[i][j] = vector[i]/vector[j];
        }
    }
    return Tem;
} 

现在我想用linq而不是for loop转换为C#语法(如何查询二维List)并使用二维List<List<double>>而不是matrix.此外,如何声明具有给定尺寸的二维ListZ*Y?

Now I want to translate into C# syntax with linq instead of for loop(how to query the two dimensional List) and use two dimensional List<List<double>> instead of matrix. Furthermore, how to declare the two dimensional List with given size say Z*Y?

推荐答案

像这样吗?

List<List<double>> GetFactors(double[] vector, int limit){
     return vector.Take(limit).Select(i => vector.Select(j => i/j).ToList()).ToList(); 
} 

将第一维限制为vector的前Z个元素(在这种情况下为limit)

Limit the first dimension to the first Z (limit in this case) elements of vector

vector.Take(limit)

对于每个值,选择一个vector[i] / vector[j](总共Y个元素)列表

For each of those values select a list of vector[i] / vector[j] (Y elements in total)

.Select(i => vector.Select(j => i/j).ToList()

并将所有列表作为列表(双精度列表的列表)返回

And return all lists as list (list of list of double)

.ToList()

您可能想向j => i/j添加一些零处理,例如:

You might want to add some zero handling to j => i/j, e.g.:

j => Math.Abs(j) < double.Epsilon ? i/j : 0.0

这篇关于使用C#LINQ编写具有二维列表的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆