How to get a list of grouped values ​​in linq groupby?

Linq is new here, fighting my first group on request.

I have a list of objects of type KeywordInstance that represent the keyword, and the identifier of the database record to which the keyword was applied.

Keyword RecordID macrophages 1 macrophages 2 cell cycle 3 map kinase 2 cell cycle 1 

I want to have a set of all keywords with a list of RecordIDs to which each keyword has been applied

 Keyword RecordIDs macrophages 1, 2 cell cycle 1, 3 map kinase 2 

I tried using Linq to get it into a new object. I managed to get only individual keywords.

var keywords = allWords .GroupBy (w => w.keyword). Select (g => new {keyword = g.Key});

The problem is that I just can't get the g values. g is of type IGrouping and according to the documentation, it has only the Key property, but even the Value property. All the examples that I saw on the Internet for the group, I’ll just say that I choose g myself, but the result

 var keywords = allWords .GroupBy(w => w.keyword) .Select(g => new {keyword = g.Key, RecordIDs = g}); 

not what i want.

screenshot of result

Any attempt to get something from g will System.Linq.IGropuing<string, UserQuery.KeywordInstance> does not have a definition for [whatever I tried] with the error System.Linq.IGropuing<string, UserQuery.KeywordInstance> does not have a definition for [whatever I tried] .

What am I doing wrong here?

+6
source share
1 answer

I think you are close to your decision.

 var keywords = allWords .GroupBy(w => w.keyword) .Select(g => new { keyword = g.Key, RecordIDs = g.Select(c => c.ID) }); 

Just Select records you need.
The reason you see the keyword column as well as the identity column is because it is part of g

+15
source

Source: https://habr.com/ru/post/957504/


All Articles