我对linq有疑问。
class Parent
{
int ParentId {get; set;}
string WhyNoChildren {get; set;}
List<Child> Children {get; set;}
}
class Child
{
String Name {get; set;}
}
父表:
ParentId | WhyNoChildren
123 | ""
567 | ""
421 | "No Kids Cause of No Money"
543 | ""
子表:
FK_ParentId | Name
123 | "Tom"
567 | "Jessy"
543 | "Bob"
我想按Child.Name分组,但我需要考虑父亲没有孩子。在这种情况下,我的结果应该是Parent.WhyNoChilden。
E.g。结果应如下所示:
ParentId | Child.Name
123 | "Tom"
567 | "Jessy"
421 | "No Kids Cause of No Money"
543 | "Bob"
linq查询应该是什么样的建议?
谢谢和问候, Rayk
答案 0 :(得分:1)
这个怎么样:
var group =
parents
.SelectMany(x =>
x.Children
.Select(y => y.Name)
.DefaultIfEmpty(x.WhyNoChildren)
.Select(y => new { ParentId = x.ParentId, ChildName = y}))
.GroupBy(x => x.ChildName);