Hey there, I have this foreach loop that doesnt work 100%. Basically I am outputting a string. My problem is I dont want sb.Append(","); to be added the last record in the loop. IS there an easy way using linq to solve this?
sb.Append("Readings:[");
foreach (var reading in lake.Reading)
{
sb.Append("[");
sb.Append("\"");
sb.Append(reading.DateTime.ToString("dd-MMM-yy"));
sb.Append("\"");
sb.Append(",");
sb.Append(reading.Level);
sb.Append("]");
//only insert this line if its the not the last record sb.Append(",");
}
sb.Append("]");
You should look into using String.Join() or String.Concat(). It makes making (comma-separated) lists as strings that much easier. And works nicely with LINQ.
var combine = from r in lake.Reading
select String.Format("[\"{0:dd-MMM-yy}\",{1}]", r.DateTime, r.Level);
var str = String.Format("Readings:[{0}]", String.Join(",", combine));
Not a Linq approach, but you could do this:
sb.Append("Readings:[");
bool isFirst = true;
foreach (var reading in lake.Reading)
{
if( isFirst == false )
{
sb.Append( "," );
}
isFirst = false;
sb.Append("[");
sb.Append("\"");
sb.Append(reading.DateTime.ToString("dd-MMM-yy"));
sb.Append("\"");
sb.Append(",");
sb.Append(reading.Level);
sb.Append("]");
}
sb.Append("]");
Even with Linq you would need to check if you are either on the first item or on the last.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With