[英]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. 我有一个查询表达式的列表,我想使用其中的值,但是我不想使用foreach,因为如果找到正确的值,我就不希望它再次循环。
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. 我不能使用SingleOrDefault,因为有多个值,我不能使用firstordefault,因为那样的话它将为我提供我在其间所有子句中找到的第一个值。 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. 但是现在我不能,因为没有最小值或最大值,并且返回的唯一值是价格和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.
第二个if子句不起作用,因为它不断循环并假定错误的答案。 Keep in mind GetPartnerProducts() is a query expression
请记住,GetPartnerProducts()是查询表达式
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?
还是我理解不正确?
but I don't want to use foreach because if it finds the right value, I dont want it looping again.
但我不想使用foreach,因为如果找到正确的值,我就不希望它再次循环。
If I understand correctly, what you want is to exit the foreach loop without completing the loop for the whole list. 如果我理解正确,那么您要退出foreach循环而不完成整个列表的循环。
You can do something like this: 您可以执行以下操作:
foreach (var c in duesproductP)
{
if(somecondition_met)
break; //this will exit the for loop
}
just break
once your conditions are met: 只要满足条件就
break
:
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;
}
Or if you also want to avoid the use of break; 或者,如果您也想避免使用break; simply put a return statement when the condition met.
满足条件时,只需放置一个return语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.