Click here to Skip to main content
14,691,598 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:

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.


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.
Updated 18-Jul-16 0:18am

You don't need the ToList(), but if you are working on a dataset that comprises multiple items then you're going to need a loop. In terms of performance your code could be improved by using StringBuilder rather than string concatenation.

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();
Member 8010354 18-Jul-16 5:22am
In the line string results = sb.ToString();, i am getting an error near results variable stating "A local variable results cannot be declared in this scope because it could give a different meaning for results which is already used in a parent or current scope to denote something else."
Can i use any other word?
You can take first object from the list
var res=detailresults.Results.Select(x=>x.Artifact).FirstOrDefault();

and then set the string
STRBODY += res[fieldname] + ";" + res[Field name2];

Note: Check res is not null before using res object.
Member 8010354 18-Jul-16 5:56am
Thank you so much. It's working fine but there is a small problem. In field name1 and fieldname2, I am using the a field where it is having the multiple choices. I want the selected choice value to be displayed but when i use the fieldname there, i am not getting the field name and selected choice value.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900