1

I have a string[][] jaggedarray like that

  1. Hello1, Hello2, Hello3
  2. Hello4, Hello5, Hello6
  3. Hello3, Hello1, Hello2

I tried going through all strings as in

foreach(var single in jaggedarray)
{

}

but I was lost due to the complexity of putting all values in an extra array and comparing each field with each field of single to make a decision.

What I did now is order every string alphabetically so

  1. Hello1, Hello2, Hello3
  2. Hello4, Hello5, Hello6
  3. Hello3, Hello1, Hello2

became

  1. Hello1, Hello2, Hello3
  2. Hello4, Hello5, Hello6
  3. Hello1, Hello2, Hello3

And then using distinct() on it.

It works that way, but I am looking for an elegant way, because now I have a lot of back and forth converting in my code.

What can a function look like that removes 1. or 3. as they contain the same values but in a different order?

Vitalis Hommel
  • 990
  • 2
  • 8
  • 20
  • Just being picky, but `string[][]` isn't a 2D array - it's a *jagged array*. `string[,]` is 2D. – Enigmativity Jun 30 '16 at 23:35
  • Can you please show the input data as valid C# code and the desired output? It would also be great if you could show what you tried, even if it didn't work or even compile. – Enigmativity Jun 30 '16 at 23:36

1 Answers1

3

This works for me:

var jaggedarray = new []
{
    new [] { "Hello1", "Hello2", "Hello3" },
    new [] { "Hello4", "Hello5", "Hello6" },
    new [] { "Hello3", "Hello1", "Hello2" },
};

jaggedarray =
    jaggedarray
        .Aggregate(
            new string[0][],
            (a, x) =>
                a.Any(y => !x.Except(y).Any())
                    ? a
                    : a.Concat(new [] { x }).ToArray());

Basically, this code starts with an empty jagged array (new string[0][]) and it iterates through jaggedarray and only adds each subarray if there doesn't exist any array with exactly the same elements. It then reassigns the final output to jaggedarray.

I get this:

result

Enigmativity
  • 113,464
  • 11
  • 89
  • 172