Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Iterate over all possible pairwise combinations of array contents

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.

like image 234
Doug Avatar asked Oct 16 '25 22:10

Doug


1 Answers

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;
}
like image 105
pkuderov Avatar answered Oct 19 '25 11:10

pkuderov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!