John Raesly
John Raesly

Reputation: 308

Use list without using foreach clause

I have a list from a query expression and I want to use the values in it but I don't want to use foreach because if it finds the right value, I dont want it looping again.

var partnerProduct = GetPartnerProducts();
var duesproductP = partnerProduct.ToList();
foreach (var c in duesproductP)
{
     //I wont include all the code in between but there are 3 if clauses
}

I cant use SingleOrDefault because there is more than one value and I cannot use firstordefault because then it will just give me the first value it finds for all of the clauses I have in between. On my other ones I had criteria where I could sort it like this:

 var duesproductsB = sectionB.Where(o => o.capg_MinCriteria.Value <= dues).ToList().OrderByDescending(o => o.capg_MaxCriteria).FirstOrDefault();

but now I can't because there is no min or max and the only values returned are the price and Id. It works for the first option and the last option but not the second. The second if clause doesn't work because it keeps looping and assumes the wrong answer. Keep in mind GetPartnerProducts() is a query expression

Upvotes: 1

Views: 66

Answers (4)

Ravi Gaurav Pandey
Ravi Gaurav Pandey

Reputation: 96

Or if you also want to avoid the use of break; simply put a return statement when the condition met.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152634

just break once your conditions are met:

List<bool> conditionsFound = new List<bool> {false,false,false};
foreach (var c in duesproductP)
{
     if(condition1)
     {
         // do something
         conditionsFound[0] = true;
     }
     if(condition2)
     {
         // do something
         conditionsFound[1] = true;
     }
     if(condition3)
     {
         // do something
         conditionsFound[2] = true;
     }

     if(conditionsFound.All())
         break;
}

Upvotes: 0

mymo
mymo

Reputation: 249

but I don't want to use foreach because if it finds the right value, I dont want it looping again.

If I understand correctly, what you want is to exit the foreach loop without completing the loop for the whole list.

You can do something like this:

 foreach (var c in duesproductP)
            {
                 if(somecondition_met)
                    break; //this will exit the for loop
            }

Upvotes: 1

user5965508
user5965508

Reputation:

Why not simply check if the value is what you expect and then break out of the loop? Or am I not understanding something correctly?

Upvotes: 4

Related Questions