linq 根据特性查找公用对象并将特性值组合到列表中

nue99wik  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(140)

我有以下n个对象列表:
第一个
找到重复项后,输出以下列表:
输出1:

[
    {
        "example": "cat",
        "categories": ["group1", "group2"]    
       
    },
    {
        "example": "dog",
        "categories": ["group1"] 
    },
    {
        "example": "cow",
        "categories": ["group1", "group3"]    
       
    },
    {
        "example": "crow",
        "categories": ["group2"] 
    }
]

使用以下代码第1部分:

public class AnimalsGrouped
{
    public string Example { get; set; }
    public string Category { get; set; }
    public List<string> Categories { get; set; }
}

var pets = input.SelectMany(x => x.Pets).ToList(); //input has the 3 lists mentioned above
var listGrouped = pets.GroupBy(x => x.Example)
   .Select(x => new AnimalsGrouped() 
    { 
        Example = x.Key, 
        Categories = x.Select(y => y.Category).Distinct().ToList() 
    })
    .ToList();

我在这些列表中有一个键“exclude”。如果exclude为真,则从输出列表中删除所有这些宠物。如果exclude为假,则将所有这些宠物添加到输出列表中。
这是我的代码第2部分:

var toInclude = input.Where(g => !g.exclude).SelectMany(x => x.Pets).ToList();
var toExclude = input.Where(g => g.exclude).SelectMany(x => x.Pets).ToList();
var diff = toInclude.Except(toExclude).ToList();

在运行该程序时,
我看到的是:
输出2:

[
    {
        "example": "dog",
        "categories": ["group1"] 
    },
        "example": "cow",
        "categories": ["group1"]    //either group1 or group3
       
    }
]

如何比较OUTPUT1和OUTPUT2的结果,找到共同的对象并输出最终列表?
最终输出应为:

[
    {
        "example": "dog",
        "categories": ["group1"] 
    },
        "example": "cow",
        "categories": ["group1", "group3"]    
       
    }
]
tvz2xvvm

tvz2xvvm1#

.Except()需要比较Pets的执行严修。在您的情况下,只有当examplecategory相同时,两个Pets才应该相等,您需要自订比较子来进行比较:

public class PetComparer: IEqualityComparer<Pet> {
  public GetHashCode(Pet p) => p.Example.GetHashCode() ^ p.Category.GetHashCode();

  public bool Equals(Pet p1, Pet p2) => p1.Example == p2.Example && p2.Category == p2.Category;
}

然后使用比较器:

var diff = toInclude.Except(toExclude, new PetComparer()).ToList();

相关问题