0

I have a list of int in c#, I want to group them in unique elements.

List<int> items = new List<int>() { 1, 3, 1, 2 };

As you can see it's have 4 element 1,3,1,2. I want to group them in size of 2. for example

[1,3],[1,2]
[1,1],[3,2]

As you can see, it's make these unique group. I am not sure how to achieve this in C#. In this case I need to group by 2, but maybe I need to group by any other number (N).

The list may contains more item than 4.

Anirudha Gupta
  • 9,073
  • 9
  • 54
  • 79
  • 1
    You want combinations without repetitions? – Tim Schmelter Dec 01 '17 at 13:54
  • What about `[2,3]`? – DavidG Dec 01 '17 at 13:54
  • @DavidG if you group [2,3] only [1,1] will remain. it doesn't matter which come first in group so [2,3] will be same as [3,2] – Anirudha Gupta Dec 01 '17 at 13:55
  • @Tim yes, but it 2 groups will be same if element are same and just index are different. – Anirudha Gupta Dec 01 '17 at 13:56
  • Did you try searching for an answer then? There's lots of examples on Stack Overflow. For example: https://stackoverflow.com/questions/5132758/words-combinations-without-repetition – DavidG Dec 01 '17 at 13:56
  • *I am not sure how to achieve this in C#*. Do you know how to do it in a language agnostic way? If you dont, then first figure that out, then try to write some code and then come here asking for help on specific problems you might be encountering. – InBetween Dec 01 '17 at 13:58
  • @DavidG Thanks for useful link, I am checking. – Anirudha Gupta Dec 01 '17 at 13:58
  • @Adrian: read [this article](https://www.codeproject.com/Articles/26050/Permutations-Combinations-and-Variations-using-C-G), tt's interesting. Then you can use the class `Facet.Combinatorics.Combination` to get all combinations without repetitions. You can use `Distinct` with a custom `IEqualityComparer>`: `var combinations = new Facet.Combinatorics.Combinations(items, 2).Distinct(new SequenceIgnoreOrderComparer());`. `Equals` of the comparer: `return Enumerable.SequenceEqual(x.OrderBy(t => t), y.OrderBy(t => t));` – Tim Schmelter Dec 01 '17 at 14:13
  • @TimSchmelter thanks, I am checking – Anirudha Gupta Dec 01 '17 at 14:20

1 Answers1

0

Just try this out, i have loaded the result to list.

List<int> numbers = new List<int>() { 1,2,3,4,5,6};
            List<int[]> numArrays = new List<int[]>();

            var numArray = numbers.ToArray();
            for(int i = 0; i < numArray.Length; i++)
            {
                for(int j = i ; j < numArray.Length; j++)
                {
                    int[] nums = new int[2];
                    nums[0] = numArray[i];
                    nums[1] = numArray[j];
                    numArrays.Add(nums);
                }
            }