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
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());
}
public Tuple<List<int>,List<int>> Convert(List<Tuple<int, int>> BaseList)
{
return new Tuple<List<int>,List<int>>((from tuple in BaseList
select tuple.Item1).ToList(),
(from tuple in BaseList
select tuple.Item2).ToList());
}
I considered it is a list of integer
, List>(new List(pairs.Count), new List(pairs.Count));
pairs.ForEach(pair =>
{
unpacked.Item1.Add(pair.Item1);
unpacked.Item2.Add(pair.Item2);
});`
– Adam Houldsworth Jul 27 '12 at 14:12