linq按两列分组并仅按值获取具有相同分组的行

时间:2021-07-08 09:21:32

标签: c# linq group-by

我想使用 LINQ 按两列( Parent_IdName )分组检索数据,并仅获取按值分组的行的结果。

Child
---------
Id        Parent_Id      Name
1         1              c1
2         1              c2
3         2              c1 <-----
4         2              c1 <-----
5         3              c2
6         3              c3
7         4              c4 <-----

如您所见,对于 Parent_Id 12Name 是不同的。所以,我不知道那些行。
我想要的结果就像

Parent_Id   Name
2           c1 
4           c4

我尝试过的是

from c in Child
group c by new
    {
        c.Parent_Id,
        c.Name
    } into gcs
    select new Child_Model()
    {
        Parent_Id = gcs.Key.Parent_Id,
        Name= gcs.Key.Name
    };

但它返回所有行。

4 个答案:

答案 0 :(得分:2)

按照您的描述,您应该仅按 Parent_id 分组并获取具有不同 Name 的组:

var result = children
    .GroupBy(c => c.Parent_Id)
    .Where(g => g.Select(t => t.Name).Distinct().Count() == 1)
    .Select(g => new
    {
        Parent_Id = g.Key,
        Name = g.Select(c => c.Name).First()
    });

答案 1 :(得分:1)

根据 Gert Arnold 的要求缩减为最终编辑:

var result = from r in (from c in children
             where !children.Any(cc => cc.Id != c.Id &&
                cc.Parent_Id == c.Parent_Id &&
                cc.Name != c.Name)
             select new  {
                Parent_Id = c.Parent_Id,
                Name = c.Name
             }).Distinct().ToList()
             select new Child_Model
             {
                Parent_Id = r.Parent_Id,
                Name = r.Name
             };

答案 2 :(得分:0)

您可以添加条件来过滤结果 (groupName.Count() > 1):

from c in childs 
group c by new { c.Parent_Id, c.Name } into gcs 
where gcs.Count() > 1 
select new { gcs.Key.Parent_Id, gcs.Key.Name }

答案 3 :(得分:0)

var myModel = Child.GroupBy( c => $"{c.Parent_Id}|{c.Name}",
          (k, list) => new Child_Model{
              Parent_Id = list.First().Parent_Id,
              Name = list.First().Parent_Id,
              Count = list.Count()})
          .Max (cm => cm.Count);
相关问题