gpt4 book ai didi

c# - Linq OrderBy 对具有相同集合的对象进行分组

转载 作者:太空狗 更新时间:2023-10-29 20:15:45 25 4
gpt4 key购买 nike

我有一组对象,它们本身包含一个集合。

private class Pilot
{
public string Name;
public HashSet<string> Skills;
}

这是一些测试数据:

public void TestSetComparison()
{
var pilots = new[]
{
new Pilot { Name = "Smith", Skills = new HashSet<string>(new[] { "B-52", "F-14" }) },
new Pilot { Name = "Higgins", Skills = new HashSet<string>(new[] { "Concorde", "F-14" }) },
new Pilot { Name = "Jones", Skills = new HashSet<string>(new[] { "F-14", "B-52" }) },
new Pilot { Name = "Wilson", Skills = new HashSet<string>(new[] { "F-14", "Concorde" }) },
new Pilot { Name = "Celko", Skills = new HashSet<string>(new[] { "Piper Cub" }) },
};

我想使用 OrderBy在 Linq 中,以便:

  • Smith 和 Jones 被安排在一起,因为他们驾驶同一架飞机
  • 希金斯和威尔逊被安排在一起,因为他们驾驶同一架飞机
  • Higgins+Wilson 是在 Smith+Jones 之前还是之后结束并不重要
  • 最好是 Smith 在 Jones 之前(稳定排序),但这不是太重要

我想我需要实现一个 IComparer<Pilot>传入 OrderBy但不知道如何处理“无关紧要”方面(上图)和稳定排序。

更新:

我希望输出是相同五个数组 Pilot对象,但以不同的顺序

最佳答案

GroupBy你必须实现 IEqualityComparer<T>对于您要分组的类型(在您的情况下为 HashSet<string>),例如

private sealed class MyComparer : IEqualityComparer<HashSet<string>> {
public bool Equals(HashSet<string> x, HashSet<string> y) {
if (object.ReferenceEquals(x, y))
return true;
else if (null == x || null == y)
return false;

return x.SetEquals(y);
}

public int GetHashCode(HashSet<string> obj) {
return obj == null ? -1 : obj.Count;
}
}

然后使用它:

 IEnumerable<Pilot> result = pilots
.GroupBy(pilot => pilot.Skills, new MyComparer())
.Select(chunk => string.Join(", ", chunk
.Select(item => item.Name)
.OrderBy(name => name))); // drop OrderBy if you want stable Smith, Jones

Console.WriteLine(string.Join(Environment.NewLine, result));

结果:

 Jones, Smith
Higgins, Wilson
Celko

编辑:如果您想要一个数组重新排列,那么添加SelectMany()为了展平分组和最后的ToArray() :

 var result = pilots
.GroupBy(pilot => pilot.Skills, new MyComparer())
.SelectMany(chunk => chunk)
.ToArray();

Console.WriteLine(string.Join(", ", result.Select(p => p.Name)));

结果:

 Jones, Smith,
Higgins, Wilson,
Celko

请注意,string.join 将每个组的名称组合在一行中,即 Jones, Smith两者具有相同的技能组合。

DotNetFiddle 运行

关于c# - Linq OrderBy 对具有相同集合的对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49749307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com