根据特性查找常见对象,并将特性的值组合到列表中



我有以下n个对象列表:

{    
"Pets": [
{
"example": "cat",
"category": "group1"  

},
{
"example": "dog",
"category": "group1"

},
{
"example": "cow",
"category": "group1"

}
],
"exclude": false
}
{    
"Pets": [
{
"example": "crow",
"category": "group2"            
},
{            
"example": "cat",
"category": "group2"
},
],
"exclude": true
}
{    
"Pets": [
{              
"example": "cow",
"category": "group3" 
}
],
"exclude": false
}

找到重复项后,我输出以下列表:

输出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为true,请从输出列表中删除所有宠物。如果exclude为false,则将所有这些宠物添加到输出列表中。

这是我的代码第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"]    

}
]

.Except()需要比较Pets的实例。在您的情况下,只有当examplecategory相同时,两个宠物才应该相等,您需要自定义比较器:

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();

最新更新