本文介绍了如何在foreach循环中停止迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





下面是代码,它应该在变量STRBODY中显示文本。但由于它是for循环,它需要多次迭代并显示所有值,但我希望它只返回一个值。



代码:



foreach(var res in detailresults.Results.Select(x => x.Artifact).ToList())

{

STRBODY + = res [fieldname] +; + res [字段名称2];

}



// detailresults是对象



任何人都可以帮助我在没有迭代的情况下以不同的方式编写相同的逻辑吗?喜欢IF条件等。



我尝试过:



我尝试通过编写IF条件调整代码但由于我的语法而失败。

Hi,

Below is the code where it should present the text inside the variable STRBODY. but as it is in for loop, it is taking multiple iterations and displaying all the values but i want it to return only one value.

Code:

foreach(var res in detailresults.Results.Select(x=>x.Artifact).ToList())
{
STRBODY += res[fieldname] + ";" + res[Field name2];
}

//detailresults is the object

Can anyone help me the same logic that i can write in different way without iterations? like IF condition and so on.

What I have tried:

I tried tweaking the code by writing IF condition but it fails due to my syntax.

推荐答案

System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(var res in detailresults.Results.Select(x=>x.Artifact))
 {
    sb.AppendFormat("{0};{1}", res[fieldname], res[fieldname2]);
 }

 string results = sb.ToString();


var res=detailresults.Results.Select(x=>x.Artifact).FirstOrDefault();



然后设置字符串


and then set the string

STRBODY += res[fieldname] + ";" + res[Field name2];





注意:在使用res对象之前检查res不为空。



Note: Check res is not null before using res object.


这篇关于如何在foreach循环中停止迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 03:27
查看更多