c# - 使用 LINQ 选择具有相同子集合的项目

标签 c# linq

这是伪案例:

class parent{
   string name; //Some Property
   List<int> myValues;

   .......
}
........
//Initialize some parent classes

List<parent> parentList = new List<parent>();
parentList.add(parent123); //parent123.myValues == {1,2,3}
parentList.add(parent456); //parent456.myValues == {4,5,6}
parentList.add(parentMatch); //parentMatch.myValues == {1,2,3}

我的目标是检索父对象列表的查询,其中 myValues 列表是等效的。在这种情况下,它将返回 parent123 和 parentMatch。

最佳答案

因此,如果您实现了 IEqualityComparer,那么您可以将逻辑包装起来并仅使用 GroupBy:

class IntegerListComparer : IEqualityComparer<List<int>>
{
    #region IEqualityComparer<List<int>> Members

    public bool Equals(List<int> x, List<int> y)
    {
        //bool xContainsY = y.All(i => x.Contains(i));
        //bool yContainsX = x.All(i => y.Contains(i));
        //return xContainsY && yContainsX;
        return x.SequenceEqual(y);
    }

    public int GetHashCode(List<int> obj)
    {
        return 0;
    }

    #endregion
}

这样调用它:

var results = list
    .GroupBy(p => p.MyValues, new IntegerListComparer())
    .Where(g => g.Count() > 1)
    .SelectMany(g => g);

关于c# - 使用 LINQ 选择具有相同子集合的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3671068/

相关文章:

c# - 拆分列表中的每个两个单词的字符串,比较是否相同并使用 Linq 进行计数

c# - ReIndex Number List 但按顺序保留重复项 C#

c# - 在linq中的两列之间选择最大值

c# - Linq to XML - 根据 if 语句设置 Xelement 值

c# - 使用 BasicHttpBinding 进行身份验证的 WCF 服务

c# - HoloLens 2 对 Windows on ARM 的 gRPC 支持

c# - 在单晶报告查看器中加载多个报告

c# - 如何访问 LINQ 查询中的关联?

c# - 如何在 GeckoFX 中设置用户代理?

c# - 从 C# Windows 窗体调用 PHP Web 服务