简体   繁体   English

按条件分组列表以创建列表列表

[英]group list by condition to create list of lists

I have a List<type1> listOfObjects and a static method我有一个List<type1> listOfObjects和一个static方法

bool CheckIfObjectsAreEquivalent(type1 obj1, type1 obj2) . bool CheckIfObjectsAreEquivalent(type1 obj1, type1 obj2)

I would like to group the list by the equivalence criteria , ie have List<List<type1>> result where each list consists of the objects that are equivalent according to CheckIfObjectsAreEquivalent .我想按等效标准对列表进行分组,即有List<List<type1>> result ,其中每个列表都包含根据CheckIfObjectsAreEquivalent等效的对象。

Another important aspect is, that I do not know upfront how many different lists will result from this grouping, as all objects could be equivalent or none or any possible number of equivalence groups.另一个重要方面是,我不知道这个分组会产生多少个不同的列表,因为所有对象可能是等价的,或者没有或任何可能数量的等价组。 The initial list of objects listOfObjects can consist of variously many objects and to see if two of those objects are equivalent one must use CheckIfObjectsAreEquivalent .对象的初始列表listOfObjects可以由不同数量的对象组成,要查看其中两个对象是否等效,必须使用CheckIfObjectsAreEquivalent

I've been looking into different options using .Where and .GroupBy but I can't get it to work...我一直在研究使用.Where.GroupBy不同选项,但我无法让它工作......

Any ideas?有任何想法吗? Thanks in advance提前致谢

You can implement IEqualityComparer<type1> interface and then use the implementation in GroupBy :您可以实现IEqualityComparer<type1>接口,然后在GroupBy使用实现:

public sealed class MyEqualityComparer : IEqualityComparer<type1> {
  public bool Equals(type1 x, type1 y) {
    // Your method here
    return MyClass.CheckIfObjectsAreEquivalent(x, y);
  }

  public int GetHashCode(type1 obj) {
    //TODO: you have to implement HashCode as well
    // return 0; is the WORST possible implementation
    // However the code will do for ANY type (type1)
    return 0; 
  }
}

Then you can put:然后你可以放:

var result = listOfObjects
  .GroupBy(item => item, new MyEqualityComparer())
  .Select(chunk => chunk.ToList()) // Let's have List<List<type1>> 
  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM