如何获得linq groupby中分组值的列表? [英] How to get a list of the grouped values in linq groupby?
问题描述
我有一个KeywordInstance类型的对象列表,它代表一个关键字,并且数据库的ID该关键字应用于的记录。
关键字RecordID
巨噬细胞1
巨噬细胞2
细胞周期3
地图激酶2
细胞周期1
我想要的是所有关键字的集合,与每个关键字应用到的RecordID列表
关键字RecordIDs
巨噬细胞1,2
细胞周期1,3
map激酶2
我尝试使用Linq将它变成新对象。我只设法得到不同的关键字。
var keywords = allwords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key });
问题是我似乎无法以任何方式获得g的值。 g是IGrouping类型,并且通过文档,它只具有属性Key,但不包括属性Value。我在互联网上看到的所有例子都只是告诉我选择g本身,但是结果是
var keywords = allWords
.GroupBy(w => w.keyword)
.Select(g => new {keyword = g.Key,RecordIDs = g});
不是我想要的。
任何尝试从g中获取某些内容都会失败,并显示错误消息 System.Linq.IGropuing< string,UserQuery.KeywordInstance>没有[我尝试过的]
的定义。
我在这里做错了什么?
我认为您已经接近您的解决方案。
var keywords = allwords
.GroupBy(w => w.keyword)
.Select(g => new
{
keyword = g.Key,
RecordIDs = g.Select(c => c.ID)
});
只需选择
您需要的记录。<
您看到 Keyword -column以及 ID -column的原因是因为它是 g的一部分
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.
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?
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
这篇关于如何获得linq groupby中分组值的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!