开发者

LINQ group one type of item

开发者 https://www.devze.com 2022-12-30 02:42 出处:网络
I have a List that has various derived classes.I may have something l开发者_如何学编程ike this:

I have a List that has various derived classes. I may have something l开发者_如何学编程ike this:

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

I am trying to use LINQ to semi-sort the list so that the natural order is maintained EXCEPT for Class2. All Class2 instances should be grouped together at the place that the first Class2 occurs. Here is what the output should be like:

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

I can't for the life of me figure out how to do this...


You can do it like this:

list = list
    .TakeWhile(o => !(o is Class2))
    .Concat(list.Where(o => o is Class2))
    .Concat(
        list.SkipWhile(o => !(o is Class2)).Where(o => !(o is Class2))
    )
    .ToList();

This will take all of the items until the first Class2 item, followed by all of the Class2 items, followed by all remaining non-Class2 items.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号