Concatenate Strings In For Each Loop

Viewed 417

I am using two for each loops to concatenate values into ONE variable so I can write the value to Word in a Find/Replace method. My issue is that the below syntax will write the values to the Console twice so this is written to the Console

Shirt - SH11
Hat - HA22
Socks - SO33
Shirt - SH11
Hat - HA22
Shirt - SH11

What I desire to be written to the console is the values just once like the below:

Shirt - SH11
Hat - HA22
Socks - SH11

This is my syntax:

DataTable table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("ItemsSold", typeof(string));
table.Columns.Add("ItemIDs", typeof(string));
table.Rows.Add("James Jo", "Shirt; Hat; Socks;", "SH11; HA22; SO33");

var itemsSold = table.Rows[0].Field<string>("ItemsSold").Split(new string[] {"; "}, StringSplitOptions.RemoveEmptyEntries);
var ItemIDs = table.Rows[0].Field<string>("ItemIDs").Split(new string[] {"; "}, StringSplitOptions.RemoveEmptyEntries);

string displayformat = "";

foreach (string is in itemsSold)
{
    foreach (string id in ItemIDs)
    {
        string s = is.Replace(";", "");
        string d = id.Replace(";", "");
        displayformat += s + " - " + d + Environment.NewLine;
    }
}

Console.WriteLine(displayformat);
2 Answers

If you really want to do this in loop, you need to modify it as

for(int i=0;i<itemsSold.Count();i++)
{
    string s = itemsSold[i].Replace(";", "");
    string d = ItemIDs[i].Replace(";", "");
    displayformat += s + " - " + d + Environment.NewLine;
}

But, please note that this can be easily done with the Zip Method. Instead of the entire Loop, you can write

displayformat = string.Join(Environment.NewLine,
                     itemsSold.Zip(ItemIDs, 
                     (items, ids) => $"{items} - {ids}").Replace(";",string.Empty));
Console.WriteLine(displayformat);

You can read on Enumerable.Zip in here

You can also use Distinct() key word. hold the value into list and filter by Distinct()

Related