开发者

Simple LINQ query

开发者 https://www.devze.com 2023-03-11 23:44 出处:网络
How would I convert the following using LINQ? foreach (int[] arr in jaggedArray) { if (arr[7] == 1) { if (!CheckThis(arr))

How would I convert the following using LINQ?

foreach (int[] arr in jaggedArray)
{
    if (arr[7] == 1)
    {
        if (!CheckThis(arr))
            boolSuccess = false;
        else
     开发者_开发技巧       intCount++;
    }
}


Something like this:

var filtered = jaggedArray.Where(arr => arr[7] == 1);
var intCount = filtered.Where(ar => CheckThis(ar)).Count()
var boolSuccess = filtered.Count() == intCount;


Nested query has to be written for the same logic or else the source code logic has to be simplified first to get a simple query


I use ReSharper, which suggests when a Linq expression is better - and performs the translation. Sometimes I keep my code though, when the Linq becomes too complex and hard to understand.


I believe this would work: First, it sets intCount by getting all of the items that satisfy arr[7]==1 and pass the CheckThis() method. That should be your intCount value.

Then, if the value in intCount doesn't match the length of the array, at least one thing failed, so you can set boolSuccess to false.

Please note that I consider this solution to be more clever, and less readable. Less readable is always a bad thing. Plus, you could refactor your existing method easily, whereas doing it this way would be much harder to refactor due to the Cleverness Factor.

        intCount = jaggedArray.Where(x => x[7] == 1).Where(CheckThis).Count();
        if (intCount != jaggedArray.Length) boolSuccess = false;


You can use Array.ForEach, although I think what you started with is actually clearer

Array.ForEach(jagged, arr => 
{ 
    if (arr[7] == 1) 
    { 
        if (!CheckThis(arr)) 
        { 
            boolSuccess = false; 
        } 
        else 
        { 
            intCount++; 
        } 
     } 
});


intCount += jaggedArray
  .Where(arr => arr[7] == 1)
  .Select(arr => 
  {
    int val = CheckThis(arr) ? 1 : 0;
    if (val == 0) {boolSuccess = false;}
    return val;
  }).Sum()
0

精彩评论

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