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
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);
}
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;
});
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With