If I have a C# array of objects and want to iterate over all pairwise combinations, how is this best accomplished? For:
int[] list = new int[3] {100, 200, 300};
This would look like:
100, 200
100, 300
200, 300
Obviously, I want a function that can take an array of any size, and preferably is generic so that any object type could work.
Try this:
public static IList<Tuple<T,T>> GetPairs<T>(IList<T> list)
{
IList<Tuple<T,T>> res = new List<Tuple<T,T>>();
for (int i = 0; i < list.Count(); i++)
{
for (int j = i + 1; j < list.Count(); j++)
{
res.Add(new Tuple<T, T>(list[i], list[j]));
}
}
return res;
}
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