4

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.

1
  • Why not just use a nested loop? Commented Sep 18, 2013 at 3:00

3 Answers 3

6

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; } 
Sign up to request clarification or add additional context in comments.

Comments

2
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]}); } } 

3 Comments

the first loop should have loop condition as i<input.Length-1
I don't see why? I just ran it and have the exact results he wishes.
Yes, but the last loop i=input.Length-1 is redundant, at that loop j=input.Length and nothing is executed more, I don't mean you code doesn't work, just redundant a little.
-1
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.

5 Comments

this may output 800 11 and 11 800, which is not what the OP wants.
This provides all permutations, not all combinations.
@Doug My code provides exact solution as Your sample question data is.
(You'll want to use WriteLine instead of Write.)
The down vote should be there, as you use 'if (i != j)' instead of just initializing j to i + 1. This is a check that is totally unnecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.