Niklas Raab Niklas Raab - 4 months ago 41
C# Question

Convert List To List of Tuples C#

How can i convert a List of Items to a List of Tuples.

Example 1:
Sourcelist [item1]
Destinationlist [{item1, null}]

Example 2:
Sourcelist [item1, item2]
Destinationlist [{item1, item2}]

Example 2:
Sourcelist [item1, item2, item3]
Destinationlist [{item1, item2}, {item3, null]]


First use the overload of Select that includes the index. Then group on the index divided by 2. Finally put the grouping, which will have one or two items into the Tuple.

var result = source.Select((v,i) => new { Index = i, Value = v })
    .GroupBy(x => x.Index/2, x => x.Value)
    .Select(g => Tuple.Create(g.First(), g.Skip(1).FirstOrDefault()));