Click here to Skip to main content
15,897,371 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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.
Posted
Updated 17-Jul-16 23:18pm

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.

C#
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();
 
Share this answer
 
v2
Comments
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
C#
var res=detailresults.Results.Select(x=>x.Artifact).FirstOrDefault();

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


Note: Check res is not null before using res object.
 
Share this answer
 
Comments
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