Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

group by - How to get a list of the grouped values in linq groupby?

Linq newbie here, struggling with my first group by query.

I have a list of objects of type KeywordInstance which represent a keyword, and the ID 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

What I want to have is a collection of all keywords, with a list of the RecordIDs to which each keyword was 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 only managed to get the distinct keywords.

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

The problem is that I can't seem to get the values of g in any way. g is of the type IGrouping and by documentation, it only has the property Key, but not even the property Value. All the examples I have seen on the Internet for groupby just tell me to select g itself, but the result of

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

is not what I want.

screenshot of result

Any try to get something out of g fails with the error message System.Linq.IGropuing<string, UserQuery.KeywordInstance> does not have a definition for [whatever I tried].

What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are close to you solution.

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

Just Select the records you need.
The reason you are seeing the Keyword-column as well as the ID-column, is becuase it's part of g


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...