假设有两个类,Person和Pet。每个人都有一个或多个宠物的集合。我如何将这个人分组到一个集合中,让他们共享相同的宠物。
示例:
人物1:猫、狗、蜘蛛
人物2:猫、蜘蛛、蛇
人物3:狗
人物4:蜘蛛,猫,狗
人物5:狗
我想要的结果是:
组1:人1,人4
第二组:第三人,第五人
组3:人员2
如何使用LINQ实现这一点?
发布于 2010-05-27 12:47:54
一种方法是从宠物中构建一个类似的密钥。例如,此方法对宠物进行排序,然后将它们组合成一个以'|‘分隔的字符串
private static string GetPetKey(Person x)
{
return String.Join("|", x.Pets.OrderBy(y => y).ToArray());
}带宠物的人:“蜘蛛”,“猫”,“狗”得到钥匙:“猫|狗|蜘蛛”
然后将其用作您的LINQ分组密钥
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 5https://stackoverflow.com/questions/2915810
复制相似问题