How to separate values by ";" in foreach loop for each item using C#

Advertisements

I have a foreach loop iterating each item at a time, I want to separate each item by using ";"
But not adding ";" for the last item.
I have tried using String.Join(";", item), But it did not work for me.

I get the output as : SN-123SN-456SN-789

Output should look something like this: SN-123;SN-456;SN-789

Please find my code below:

if (siteId != "null")
{
    var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
    List<string> siteSNlist = siteList.Gateways.Select(x => x.SerialNumber).ToList();
    foreach (var item in siteSNlist)
    {
        siteSN += String.Join(";", item);
    }
}

>Solution :

You need to use string join for a collection, try like this:

if (siteId != "null")
{
  var siteList = this.feeDataAccess.GetSitesListById(connectedUser.CurrentEnvironment, siteId);
  List<string> siteSNlist = siteList.Gateways.Select(x => x.SerialNumber).ToList();
                
  siteSN = String.Join(";", siteSNlist);
                
}

For the nested objects you can use select:

if (partnerId != "null")
{
    var partnerList = this.feeDataAccess.GetPartnerListbyId(connectedUser.CurrentEnvironment, partnerId);
    foreach (var item in partnerList)
    {
        var partnerSN = string.Join(";", item.Gateways.Select(x => x.SerialNumber));
    }
}

Leave a ReplyCancel reply