0

I have this issue that I am currently stuck with in C#. I have about 31 columns of data within Jobject inside Jarray (JArray tableJson = new JArray();)

I would like to group them into three columns. So far I can only group by one of the columns eg :

var tableJsonGroup = tableJson.GroupBy(x => x["FirstColumn"]).ToList(); 

I want to do something like this (it does not work) :

var tableJsonGroup = tableJson.GroupBy(x => new {x["FirstColumn"], x["SecondColumn"], x["FifthColumn"]}).ToList(); 

How do I do this?

Thank you.

eko
  • 33
  • 4
  • JSON arrays are not tables and they don't have columns.. You're actually referring to JSON object properties. – Dai Jul 19 '22 at 06:10
  • _"I want to do something like this (it does not work)"_ **how** is it not working? Do you get a compiler error or a runtime error or just unexpected results? – Dai Jul 19 '22 at 06:11
  • _"I would like to group them into three columns"_ - I think you mean you want to _group **by**_ three properties, not "group _into_" three columns. – Dai Jul 19 '22 at 06:12

1 Answers1

0

As we can see, this overload of the GroupBy extension takes a delegate which is used to enumerate the tableJson and generate a key for each item.

Items that generate the same key will be grouped together and returned as an IGrouping. There is no special treatment based on the type of the source. This doesn't do anything different, whether you have an array of ints or an array of complex objects.

So, if you want to group by a combination of columns you need to provide a function that returns a unique, repeatable, key for that combination of columns.

This can be simply achieved by compounding those columns into an anonymous type, which has a built in implementation for equality and hashing that suits our purposes, like in this answer.

var groupedTableJson = tableJson.GroupBy(x =>
    new {
        FirstColumn: x["FirstColumn"],
        SecondColumn: x["SecondColumn"],
        FifthColumn: x["FifthColumn"]
    });

Your answer is almost right but, you don't provide names for properties of your anonymous type. However, since you don't explain what "does not work", it is hard to be sure.

Jodrell
  • 34,946
  • 5
  • 87
  • 124