Muhammad Sadiq Muhammad Sadiq - 6 months ago 29
Vb.net Question

LINQ Concate Two List To make one csv list

I have two list with different number of items like.

a = {"a","b","c","d","e"}<br>
b = {"f","g","h"}


Now I want this final output from these list.

a,f
b,g
c,h
d
e


If the list were reversed like

a = {"f","g","h"}
b = {"a","b","c","d","e"}


The result would be

f,a
g,b
h,c
,d
,e


I tried to search on internet but my search always end up on something thike this.

Dim lst1 As List(Of String) = New List(Of String)() From {"a", "b", "c", "d", "e"}<br>
Dim lst2 As List(Of String) = New List(Of String)() From {"f", "g", "h"}

Dim res = From a In lst1, b In lst2
Select a & "," & b

For Each r In res
Debug.Print(r)
Next


Showing wrong result

a,f
a,g
a,h
b,f
b,g
b,h
c,f
c,g
c,h
d,f
d,g
d,h
e,f
e,g
e,h

Answer

More alternatives from me

var c = Enumerable.Range(0, Math.Max(a.Length, b.Length))
        .Select(i => (i < a.Length ? a[i] : "") + "," + (i < b.Length ? b[i] : ""))
        .ToList();

Or

var c = a.Select((s, i) => new { s, i })
         .Concat(b.Select((s, i) => new { s, i }))
         .GroupBy(x => x.i)
         .Select(g => string.Join(",", g.Select(x => x.s)))
         .ToList();

To see the output:

Console.WriteLine(String.Join(Environment.NewLine, c));