Doug
Doug

Reputation: 5266

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.

Upvotes: 4

Views: 1863

Answers (3)

pkuderov
pkuderov

Reputation: 3551

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;
}

Upvotes: 6

Sanket Patel
Sanket Patel

Reputation: 1160

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };      

        for (int i = 0; i < arr.Length; i++)
        {
            for (int j= i; j< arr.Length; j++)
            {
    if(i!=j)


                    //Console.Write(arr[i] + " " + arr[j]);
Console.WriteLine(arr[i] + " " + arr[j]);

            }
        }

Instead of 'int' you can take Object type. Then you need to maintain further checking.

Upvotes: -1

Charles
Charles

Reputation: 317

int[] input = new int[] {100, 200, 300};

List<int[]> result = new List<int[]>();

for(int i=0; i<input.Length-1; i++)
{
    for(int j=i+1; j<input.Length; j++)
    {
        result.Add(new int[]{input[i], input[j]});
    }
}

Upvotes: 2

Related Questions