Home > Software design >  How can I add an List with different data after loop beside existing list?
How can I add an List with different data after loop beside existing list?

Time:01-26

so bassicly I've got 2 different List

  List<string> result = new List<string>;
  List<string> outputs= new List<string>;

the outputs List getting filled in an loop and after the loop ends it will add the outputs list in the result list.

So that outputs will have this different values after the loop ends.

For example after the first loop ends the output list has data like:

exampleData1
exampleData2
exampleData3

and so on

so that the result List would now have this three example data.

Now the loop will hit again and will load different data like:

exampleData1.1
exampleData2.1
exampleData3.1

and now It should add this three example data to the result list:

so that now the result list should look like that:

exampleData1, exampleData1.1
exampleData2, exampleData2.1
exampleData3, exampleData3.1

and so should It go on after each loop after the output list changed it should be add side by side like one string.

I have tried things like that:

foreach (var (item1, item2) in output.Zip(output, (xo, y) => (xo, y)))
    result.Add($" {item1}, {item2}");

but that's only adding the existing list side by side so that I have 2x the same value side by side.

I hope I have explained it understandable and if not, pls let me know.

CodePudding user response:

Zip is good idea, but care. From the documentation :

If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them.

As result is empty, the end is reached before to start. The solution is to complete with the elements not iterated by Zip :

result = result.Zip(outputs, (r, o) => r   ", "   o)
    .Union(result.Skip(outputs.Count)) // Add element from result not iterated by Zip
    .Union(outputs.Skip(result.Count)) // Add element from outputs not iterated by Zip
    .ToList();

CodePudding user response:

Have look at this: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip?view=net-7.0 I think you have a mistake in your code. You're "zipping" outputs with outputs (i.e. itself) you need to zip it with result.

var mergedLists = result.Zip(outputs, (first, second) => first   " "   second);

UPDATED Here's a full console app solution:

List<string> result = new();
for (var i = 0; i < 3; i  )
{
    List<string> outputs = new();
    for (var j = 0; j < 3; j  )
    {
        outputs.Add($"TestData{i}.{j}");
    }

    if (!result.Any())
    {
        result = outputs.ToList();
    }
    else
    {
        result = result.Zip(outputs, (first, second) => first   " "   second).ToList();
    }
}

Console.WriteLine(string.Join(Environment.NewLine, result));
Console.ReadLine();
  • Related