Chris Morris
Chris Morris

Reputation: 11

Simple LINQ query

How would I convert the following using LINQ?

foreach (int[] arr in jaggedArray)
{
    if (arr[7] == 1)
    {
        if (!CheckThis(arr))
            boolSuccess = false;
        else
            intCount++;
    }
}

Upvotes: 1

Views: 119

Answers (6)

Amy B
Amy B

Reputation: 110111

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

Upvotes: 0

Rob
Rob

Reputation: 4477

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

Upvotes: 0

Daniel Mann
Daniel Mann

Reputation: 59018

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;

Upvotes: 0

Niklas Wulff
Niklas Wulff

Reputation: 3524

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.

Upvotes: 0

Ankur
Ankur

Reputation: 33637

Something like this:

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

Upvotes: 1

Zenwalker
Zenwalker

Reputation: 1919

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

Upvotes: 0

Related Questions