Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groupping/sorting/splitting 2D list/array

I have following 2D array

var array1 = new string[][]
            {
              new string[] {A,B,C},
              new string[] {A,X,Y},
              new string[] {D,L,K},
              new string[] {A,X,W}

            };

At the end I would like to sort or group this list and output I want to display on my MVC view on a table as below

A / X / Y,W

/ B/ C

D/ l / K

I dont want to show repeated elements in the column. So it means like groupping.

  • How can I group the results in controller with linq.
  • Sorting might also help if I can sort by first element and then 2nd etc.
  • Another idea also works that if I can split into 3 1D arrays? So at the end i would have array1 ={A,A,D,A}, array2={B,X,L,X}, array3= {C,Y,K,W}

Thanks.

like image 539
Emil Avatar asked May 23 '26 20:05

Emil


1 Answers

Your problem should be split into two subproblems. First, you need to sort the array1; second, you need out array1 using the fact the array1 is sorted.

You can't use grouping instead of sorting, cause a grouping is not guarantee that subarrays with the same first element will follow each other.

var array1 = new List<IList<string>>
{
    new List<string> {"A", "X", "Y"}, 
    new List<string> {"A", "X", "W"}, 
    new List<string> {"A", "B", "C"}, 
    new List<string> {"D", "L", "K"}, 
};

var array2 = from a in array1
    orderby a[0], a[1], a[2]  
    select a;

var array3 = array2.ToList();

Now you can use array2 in Razor:

@if (array2.MoveNext())
{
   @array2.Current[0], @array2.Current[1], @array2.Current[3]<br />

   var lastElement = array2.Current;
   while (array2.MoveNext())
   {
     if (array2.Current[0] != lastElement[0])
     {
       @array2.Current[0],
     }
     else if (array2.Current[1] != lastElement[0])
     {
       @array2.Current[1],
     }

     @array2.Current[2]
     lastElement = array2.Current;
   }
}
like image 127
Mark Shevchenko Avatar answered May 25 '26 09:05

Mark Shevchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!