Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Strings In For Each Loop

Tags:

c#

linq

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);
like image 390
Doctor Ford Avatar asked Jul 25 '26 03:07

Doctor Ford


1 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

like image 56
Anu Viswan Avatar answered Jul 27 '26 16:07

Anu Viswan



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!