Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading