LINQ组中的一个类型的项目组中、类型、项目、LINQ

由网友(每个时期都会。)分享简介:我有一个列表,具有多种派生类。我可能有这样的事情:I have a List that has various derived classes. I may have something like this:List list = new List() {new Cla...

我有一个列表,具有多种派生类。我可能有这样的事情:

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

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

我想使用LINQ到半排序列表,以便自然秩序维持,除了等级2。所有的Class2实例应该在该第一等级2发生的地点被组合在一起。以下是输出应该是这样的:

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();

这将采取所有的项目,直到第一个类2 项,然后是所有的类2 的项目,其次是所有剩余的非 - 类2 项目

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.

阅读全文

相关推荐

最新文章