Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: List of tuples to tuple of lists

Tags:

c#

linq

I have a List<Tuple<A,B>> and would like to know if there is a way in LINQ to return Tuple<List<A>,List<B>>

This is similar to the following Python question: Unpacking a list / tuple of pairs into two lists / tuples

like image 317
Ben Avatar asked Jul 27 '12 13:07

Ben


3 Answers

It's not possible with a single LINQ call, however you can do it quite easily with code:

Tuple<List<A>, List<B>> Unpack<A, B>(List<Tuple<A, B>> list)
{
  var listA = new List<A>(list.Count);
  var listB = new List<B>(list.Count);
  foreach (var t in list)
  {
    listA.Add(t.Item1);
    listB.Add(t.Item2);
  }

  return Tuple.Create(listA, listB);
}
like image 189
Martin1921 Avatar answered Oct 16 '22 05:10

Martin1921


You can use Aggregate:

Tuple<List<A>, List<B>> Unpack<A, B>(List<Tuple<A, B>> list)
{
    return list.Aggregate(Tuple.Create(new List<A>(list.Count), new List<B>(list.Count)),
                          (unpacked, tuple) =>
                          {
                              unpacked.Item1.Add(tuple.Item1);
                              unpacked.Item2.Add(tuple.Item2);
                              return unpacked;
                          });
}
like image 6
Risky Martin Avatar answered Oct 16 '22 06:10

Risky Martin


Tuple<List<A>, List<B>> Unpack<A, B>(List<Tuple<A, B>> list) {
            return Tuple.Create(list.Select(e => e.Item1).ToList(),list.Select(e => e.Item2).ToList());
}
like image 3
Gerberts Avatar answered Oct 16 '22 06:10

Gerberts