我有以下数据:
Parent Id=11
Child Name=A1
Parent Id=22
Child Name=A1
Child Name=B2
使用LINQ,我想要所有具有相同名称及其父ID的子节点,如下所示:
11, A1
22, A1
这是我创建的父和子嵌套类的结构:
public class cParent
{
public List<ChildClass> listChildClass;
public string parentId { get; set; }
}
public class ChildClass
{
public string childNAme{ get; set; }
}
答案 0 :(得分:0)
您可以使用分组来查找重复项:
var p11 = new cParent { parentId = "11" }; // assuming listChildClass is a collection
p11.listChildClass.Add(new ChildClass { childNAme = "A1" });
var p22 = new cParent { parentId = "22" };
p22.listChildClass.Add(new ChildClass { childNAme = "A1" });
p22.listChildClass.Add(new ChildClass { childNAme = "B2" });
var parents = new List<cParent> { p11, p22 };
var duplicatesByKey =
from parent in parents
from child in parent.listChildClass
let combo = new { parent.parentId, child.childNAme }
group combo by combo.childNAme into g
where g.Count() > 1
select new { g.Key, Values = g.ToList() };
如果你要实现比较器,这会更好,但我会把它留给读者。