Montague27
Montague27

Reputation: 81

Group the indexes of the same elements in a array in C#

There is a int[] array that stores different numbers.

What I want is to group the indexes of those same numbers in the array to the same groups.

For exmaple, the array is int[5]{1,2,5,1,5}

I would like to see the output is List<List<int>> { {0,3}, {1}, {2,4} } // don't mind syntax

It's better if Linq (or a more efficient way) can be used, thanks for help.

Upvotes: 0

Views: 2310

Answers (3)

Slaven Tojić
Slaven Tojić

Reputation: 3014

You can use Enumerable.Range combined with GroupBy:

int[] arr = { 1, 2, 5, 1, 5 };

var result = Enumerable.Range(0, arr.Length)
            .GroupBy(i => arr[i])
            .Select(x => x.ToList()).ToList();

DEMO HERE

Upvotes: 0

pwas
pwas

Reputation: 3373

One of ways:

var result = myArray.Select((elem, idx) => new { Value = elem, Idx = idx})
                    .GroupBy(proxy => proxy.Value);

foreach (var grouped in result)
{
   Console.WriteLine("Element {0} has indexes: {1}", 
                 grouped.Key, 
                 string.Join(", ", grouped.Select(proxy => proxy.Idx).ToArray()));
}

var myFinalList = result.Select(proxy => proxy.ToArray()).ToList();

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156988

You can simply use GroupBy and the position obtained from the Select overload:

int[] array;

var result = array.Select((v, idx) => new { Value = v, Index = idx })
                  .GroupBy(g => g.Value)
                  .Select(g => g.ToArray()) // inner array
                  .ToArray(); // outer array

Upvotes: 2

Related Questions