【问题标题】:Generic parent Collection split to child collections通用父集合拆分为子集合
【发布时间】:2013-03-09 12:44:35
【问题描述】:

我有IAnimal的列表

List<IAnimal> Animals

在这个列表中,我有 3 个不同的 Animal

  1. Cat 5 个对象
  2. Dog 10 个对象
  3. Cow 3 个对象

如何生成 3 个不同的子 Animal 类型列表?

结果应该是

  1. List&lt;Cat&gt; Cats 包含 5 个对象
  2. List&lt;Dog&gt; Dogs 包含 10 个对象
  3. List&lt;Cow&gt; Cows 包含 3 个对象

我不介意使用与 List 不同的集合类型。 IEnumerable 或其他任何人?

【问题讨论】:

    标签: c# list .net-3.5 ienumerable


    【解决方案1】:

    LINQ 让这一切变得简单:

    var cats = animals.OfType<Cat>().ToList();
    var dogs = animals.OfType<Dog>().ToList();
    var cows = animals.OfType<Cow>().ToList();
    

    【讨论】:

      【解决方案2】:

      只使用Enumerable.OfType 怎么样?

      根据指定类型过滤 IEnumerable 的元素。

      Return Value
      Type: System.Collections.Generic.IEnumerable<TResult>
      An IEnumerable<T> that contains elements from the input sequence of type TResult.
      

      var cat = animals.OfType<Cat>().ToList();
      var cow = animals.OfType<Cow>().ToList();
      var dog = animals.OfType<Dog>().ToList();
      

      【讨论】:

        【解决方案3】:

        使用foreachLINQ 遍历您的列表并检查类型:

         foreach(IAnimal animal in Animals){
          if(animal is Cat)
             Cats.Append(animal);
         //do the same with dogs and cows
         }
        

        【讨论】:

        • 请注意,您必须强制转换,方法是Add,而不是Append
        猜你喜欢
        • 1970-01-01
        • 2016-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-16
        • 2019-02-12
        • 1970-01-01
        相关资源
        最近更新 更多