LINQ - group specific types of classes

Posted by Nelson on Stack Overflow See other posts from Stack Overflow or by Nelson
Published on 2010-05-14T15:46:20Z Indexed on 2010/05/14 15:54 UTC
Read the original article Hit count: 217

Filed under:
|
|

This question is similar to http://stackoverflow.com/questions/2835192/linq-group-one-type-of-item but handled in a more generic way.

I have a List that has various derived classes. I may have something like this:

List<BaseClass> list = new List<BaseClass>() {
  new Class1(1),
  new Class2(1),
  new Class1(2),
  new Class3(1),
  new Class2(2),
  new Class4(1),
  new Class3(2)
};

I am trying to use LINQ to semi-sort the list so that the natural order is maintained EXCEPT for certain classes which have base.GroupThisType == true. All classes with GroupThisType should be grouped together at the place that the first class of the same type occurs. Here is what the output should be like:

List<BaseClass> list = new List<BaseClass>() {
  new Class1(1),
  new Class1(2),
  new Class2(1),
  new Class3(1),
  new Class3(2)
  new Class2(2),
  new Class4(1),
};

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET