Home > Blockchain >  How to concat multiple list of object in single column c#
How to concat multiple list of object in single column c#

Time:11-02

I'm facing an issue while displaying multiple lists the value in a single row column.

Here is an example of code.

public class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, List<object>> keyvalues = new Dictionary<string, List<object>>();
        keyvalues.Add("Code", new List<object>() { 1, 2, 3, 4 });
        keyvalues.Add("Name", new List<object>() { "A", "B", "C", "D" });
        keyvalues.Add("Age", new List<object>() { 20, 30, 40, 50 });        

        var listData = keyvalues.Select(x => x.Value).Select((x, i) => new { obj = x, index = i });
        var listData = keyvalues.Select((x, iparent) => x.Value.Select((z, i) => new { value = string.Concat(z, x.Value[i]) }).ToList()).ToList();
                
        Console.ReadLine();
    }
}

Expected output

1A20
2B30
3C40
4D50

CodePudding user response:

You could easily use Zip here. However, you could roll your own

public static IEnumerable<string> DoStuff<T, T2>(Dictionary<T, List<T2>> source)
{
   var max = source.Values.Max(x => x?.Count ?? 0);
   for (var i = 0; i < max; i  )
      yield return string.Concat(source.Values.Select(x => x.ElementAtOrDefault(i)));
}

Usage

var results = DoStuff(keyvalues);
Console.WriteLine(string.Join(Environment.NewLine,results));

Output

1A20
2B30
3C40
4D50

or

public static IEnumerable<string> DoStuff<T>(List<T>[] source)
{
   var max = source.Max(x => x?.Count ?? 0);
   for (var i = 0; i < max; i  )
      yield return string.Concat(source.Select(x => x.ElementAtOrDefault(i)));
}

...

var results = DoStuff(keyvalues.Values.ToArray());
Console.WriteLine(string.Join(Environment.NewLine,results));

CodePudding user response:

If you are using .Net 6, you could make use of the new 3 way Zip extension.

var result = keyvalues["Code"].Zip(keyvalues["Name"], keyvalues["Age"])
            .Select(x=> $"{x.First}{x.Second}{x.Third}");
  • Related