linq 使用多个列的Jarray GroupBy

p1tboqfb  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(302)

我在C#中遇到了一个问题,我在Jarray(JArray tableJson = new JArray())中的Jobject中有大约31列数据;)
我想把它们分成三列。到目前为止,我只能按其中一列分组,例如:

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

我想做这样的事情(它不起作用):

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

我该怎么做?

  • 谢谢-谢谢
62lalag4

62lalag41#

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 int s 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.

相关问题