skip to Main Content

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

3

Answers


  1. 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));
    
    Login or Signup to reply.
  2. 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}");
    
    Login or Signup to reply.
  3. Why make it so complicated?

    for(int x = 0; x<keyValues["Code"].Count; x++)
      Console.WriteLine(
        keyValues["Code"][x]+
        keyValues["Name"][x]+
        keyValues["Age"][x]
      );
    

    LINQ’s a hammer; not every problem is a nail.

    ps if you have N keys, you can easily turn it into a

    var keys = new[]{"Code","Name","Age","Foo","Bar"};
    for(...)
      foreach(var k in keys)
        ... //some concat here or use the values directly eg adding to your page 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search