Click here to Skip to main content
14,389,715 members
Rate this:
Please Sign up or sign in to 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 18-Jul-16 0:18am
Rate this:
Please Sign up or sign in to vote.

Solution 1

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();
   
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?
Rate this:
Please Sign up or sign in to vote.

Solution 2

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.
   
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, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100