具有相等集合的组对象 [英] group object with equal collections
问题描述
假设有2个类,人"和宠物".每个人都有1个或更多宠物的集合. 我如何将人"分组到他们共享相同宠物的集合中.
Suppose 2 classes, Person and Pet. Each person has a collection of 1 or more pets. How do i group the Person in to a collection where they share the same pets.
示例:
人1:猫,狗,蜘蛛
人2:猫,蜘蛛,蛇
人3:狗
第4个人:蜘蛛,猫,狗
Person 4: Spider, Cat, Dog
第5个人:狗
我想要的结果是这样:
第1组:第1个人,第4个人
Group 1: Person 1, Person 4
第2组:第3人,第5人
Group 2: Person 3, Person 5
第3组:第2人
我如何使用LINQ实现这一目标?
How do i achieve this using LINQ?
推荐答案
一种方法是从宠物中构建一个可比较的钥匙.例如,此方法将宠物分类,然后将它们组合成一个字符串,并用'|'
One way is to build a comparable key out of the pets. For example, this method sorts the pets then combines them into a single string separated by '|'
private static string GetPetKey(Person x)
{
return String.Join("|", x.Pets.OrderBy(y => y).ToArray());
}
带宠物的人:蜘蛛",猫",狗" 得到密钥:猫|狗|蜘蛛"
A person with the pets: "Spider", "Cat", "Dog" gets the key: "Cat|Dog|Spider"
然后将其用作LINQ分组密钥
Then use that as your LINQ grouping key
var grouped = people.GroupBy(x => GetPetKey(x))
示例实现:
var people = new List<Person>
{
new Person
{
Id = 1,
Pets = new[] { "Cat", "Dog", "Spider" }
},
new Person
{
Id = 2,
Pets = new[] { "Cat", "Spider", "Snake" }
},
new Person
{
Id = 3,
Pets = new[] { "Dog" }
},
new Person
{
Id = 4,
Pets = new[] { "Spider", "Cat", "Dog" }
},
new Person
{
Id = 5,
Pets = new[] { "Dog" }
}
};
var grouped = people.GroupBy(x => GetPetKey(x)).ToList();
grouped.ForEach(WriteGroup);
输出助手
private static void WriteGroup(IGrouping<string, Person> grouping)
{
Console.Write("People with " +String.Join(", ",grouping.First().Pets)+": ");
var people = grouping.Select(x=>"Person "+x.Id).ToArray();
Console.WriteLine(String.Join(", ", people));
}
输出:
People with Cat, Dog, Spider: Person 1, Person 4
People with Cat, Spider, Snake: Person 2
People with Dog: Person 3, Person 5
这篇关于具有相等集合的组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!