Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

better way to do this foreach using linq

Tags:

c#

linq

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("]");
like image 721
Diver Dan Avatar asked Dec 05 '25 12:12

Diver Dan


2 Answers

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));
like image 138
Jeff Mercado Avatar answered Dec 08 '25 01:12

Jeff Mercado


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.

like image 45
Viper Avatar answered Dec 08 '25 01:12

Viper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!