Nikita Silverstruk
Nikita Silverstruk

Reputation: 1117

Create pairs from List values

I have a list with some values, lets say 1 2 3 4 5 6

I need to pair them up like this: 12 13 14 15 16 23 24 25 26 34 35 36 45 46 56

Basically, I need to mix them all up to create unique sets of values.

Do you have any ideas on how to create a new list like this?

Thank you for your input!

Upvotes: 3

Views: 5493

Answers (4)

danplisetsky
danplisetsky

Reputation: 241

Using Linq and tuples:

var arr = new[] { 1, 2, 3, 4, 5, 6 };

arr.SelectMany((fst, i) => arr.Skip(i + 1).Select(snd => (fst, snd)));

Upvotes: 11

Spevy
Spevy

Reputation: 1325

If you like Linq:

var ar = new int[] {1, 2, 3, 4, 5};

var combo = (from left in ar
            from right in ar where right > left 
            select new { left, right }).ToArray();

Upvotes: 7

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

For the data from your sample you can do it with a trivial pair of nested loops:

var list = new List<int>{1,2,3,4,5,6};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(list[i]*10+list[j]);
    }
}

For more complex data, you can use a string concatenation trick:

var list = new List<int>{98,76,54,32,10};
var res = new List<int>();
for (int i = 0 ; i != list.Count ; i++) {
    for (int j = i+1 ; j != list.Count ; j++) {
        res.Add(int.Parse(string.Format("{0}{1}", list[i], list[j])));
    }
}

Upvotes: 2

Sidharth Mudgal
Sidharth Mudgal

Reputation: 4264

var newList = new List<int>();
foreach(var i in originalList)
    for(int j = i + 1; j < originalList.Count; ++j)
        newList.Add(originalList[i] * 10 + originalList[j]);

Should help...

Upvotes: 1

Related Questions