2012-04-10 84 views
1

我有一个数组,我想获得存储在数组中的每个维的长度。即我想类似以下内容:使用LINQ来获得数组的长度的长度

Array myArray = //...Blah blah myArray is defined somewhere in code 

int[] dimLengths = myArray.SomeLinqStatement... 

我可以与一些for循环(一个或多个),但我希望会有一个简单的LINQ语句做到这一点。因此,例如,如果myArray是2x3x4的3D数组,我希望dimLengths为{2,3,4}。

回答

1

你不需要LINQ。这里有一个简单的解决方案:

int[] GetDimensions(Array array) 
{ 
    int[] dimensions = new int[array.Rank]; 
    for (int i = 0; i < array.Rank; i++) 
    { 
     dimensions[i] = array.GetLength(i); 
    } 
    return dimensions; 
} 

如果必须使用LINQ,你可以试试这个,但我相信其他的方式更好:

int[] dimensions = Enumerable.Range(0, array.Rank) 
          .Select(i => array.GetLength(i)) 
          .ToArray(); 
+0

出于好奇,是什么让你“确定”非linq方式更好? – KrisTrip 2012-04-10 16:46:27

+1

经验,加上对LINQ工作方式的理解。 LINQ版本与其他版本做了相同的事情,再加上两个额外的操作:它需要生成一系列要处理的整数,并且它需要将一个IEnumerable转换为一个数组。有关该问题的知识的代码几乎总是比没有这些知识的代码快。 – 2012-04-10 16:52:17

+1

@KendallFrey:但是这种差异可以忽略不计(当然在这种情况下)。那么可读性应该始终是首选。 – 2012-04-10 16:54:00

1

为什么你需要LINQ来获得`Array的维数的长度?

myArray.GetLength(0); //returns the length of the first dimension 
myArray.GetLength(1); //returns the length of the second dimension 
myArray.GetLength(2); //returns the length of the third dimension 

Array.GetLength Method

这是你的 “性感” LINQ方法:

int[, ,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } }, 
          { { 7, 8, 9 }, { 10, 11, 12 } } }; 
var result = Enumerable.Range(0, array3D.Rank) 
     .Select(i => array3D.GetLength(i)) 
     .ToArray(); 
+1

因为我希望所有的维度长度的数组。我知道我可以使用for循环和GetLength方法。我只是想在linq的性感一条线上做到这一点:) – KrisTrip 2012-04-10 16:30:27

+0

@KrisTrip:测试我的另一种方法。 – 2012-04-10 16:38:26