2013-04-22 86 views
0

说我有一个包含狗,猫等的c#中的动物集合...我如何获得基本集合中所有属于狗的所有项目,以便我可以执行对所有狗物品的其他操作,就好像它们在它们自己的单独集合中一样,就好像它们在List<Dog>(并且对象也在基本集合中更新一样)?从基础集合中获取对象的专门集合

对于代码答案,假设List<Animals>已足够,因为如果可能的话,我想避免implementing my own generic collection

编辑:我刚刚注意到这个问题是非常相似的c# collection inheritance

+1

看起来像这个问题涵盖了它,任何你不能使用'OfType'的原因? – 2013-04-22 08:16:02

回答

1

刚刚宣布在基类基本方法,像

public class Base { 

    List<Animals> animals = .... 
    ... 
    .... 

    public IEnumerable<T> GetChildrenOfType<T>() 
     where T : Animals 
    { 
     return animals.OfType<T>(); // using System.Linq; 
    } 
} 

类似的东西。你应该自然地改变这个以适应你的确切需求。

+3

这不会编译。我想你的意思是'公共IEnumerable GetChildrenOfType (){return animals.OfType (); }'。那个基类从哪里来? – 2013-04-22 08:23:22

+0

@DanielHilgarth:谢谢,纠正。 – Tigran 2013-04-22 08:27:16

+0

您只更正了三个错误中的一个。 – 2013-04-22 08:27:45

0
List<Dog> dogList = new List<Dog>(); 
foreach(Animal a in animals) { //animals is your animal list 
    if(a.GetType() == typeof(Dog)) { //check if the current Animal (a) is a dog 
     dogList.Add(a as Dog); //add the dog to the dogList 
    } 
} 
+0

为什么不使用'OfType'? – 2013-04-22 08:21:08

+0

当然,你可以使用OfType,但我从来没有使用它,所以我使用typeof()和GetType()。 – 2013-04-22 08:22:51

+0

这对'class SpecialDog:Dog'不起作用,而空引用将抛出,而OfType ()确实处理得好 – Firo 2013-04-22 08:52:23

2

关于其他海报和使用OfType,你可以做;

List<Dog> dogList = new List<Dog>(); 

foreach(Animal a in animals.OfType<Dog>()) 
    { 
     //Do stuff with your dogs here, for example; 
     dogList.Add(a); 
    } 

现在,您已将所有的狗列入单独列表中,或者您想要对它们进行任何操作。这些狗也将仍然存在于你的基地收藏。

+0

OfType在缺少OfType后。什么原因不使用'List dogList = animals.OfType ().ToList()'? – Firo 2013-04-22 08:50:06

+0

对不起,免费打字。你也可以这样做。我想这种方式可以让你对狗做其他的事情,如果你想不止添加到另一个列表。但公平点。 – 2013-04-22 08:51:33