[英]LINQ group by into a new list
I have two classes我有两节课
public class groupedDoc {
public string gr_id = "";
public string id = "";
public string name = "";
public subrec subRec = new subrec();
}
public class subrec {
public List<record> record = new List<record>();
'''
}
I want to group a List<record> allrecord
based on the id and name into the object called groupedDoc
.我想根据 ID 和名称将
List<record> allrecord
到名为groupedDoc
的 object 中。
This is what I do这就是我所做的
var groupedList = allrecord.ToList().GroupBy(x => new { x.id ,x.name})
.Select(grp => new groupedRec
{
gr_id = Guid.NewGuid().ToString(),
id = grp.FirstOrDefault().id,
name = grp.FirstOrDefault().name
})
.ToList();
But I also want to return the grouped record into the subrec.record
.但我也想将分组记录返回到
subrec.record
中。 I tried subRec.record = grp.ToList()
but get "invalid initializer member declarator".我尝试
subRec.record = grp.ToList()
但得到“无效的初始化程序成员声明器”。 So anyone can help me to achieved that?所以任何人都可以帮助我实现这一目标?
You have to also initialize subrec in the statement:您还必须在语句中初始化 subrec:
var groupedList = allrecord.ToList().GroupBy(x => new { x.id ,x.name})
.Select(grp => new groupedRec
{
gr_id = Guid.NewGuid().ToString(),
id = grp.Key.id,
name = grp.Key.name,
subRec = new subrec()
{
record = grp.ToList()
}
})
.ToList();
I've replaced your id =
and name =
assignments with what I believe you were going for, to save creating more enumerators for the grouped records.我已将您的
id =
和name =
分配替换为我相信您想要的,以节省为分组记录创建更多枚举器。 As an aside, you should rename record
to records
as it represents more than one record.顺便说一句,您应该将
record
重命名为records
,因为它代表多个记录。
I'd also recommend following Microsoft's naming conventions so that your code is easier for other people to follow, etc.我还建议遵循Microsoft 的命名约定,以便您的代码更容易被其他人遵循等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.