المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Get one type of elements from dictionary



C# Programming
06-27-2011, 10:41 PM
I store two kinds of data types (Bar1 and Bar2) in the same dictionary. Both data types dervies from Foo class. I would like to extract only the Bar2 elements from the dictionary.

Here is what I got:
abstract class Foo{} class Bar1 : Foo{} class Bar2 : Foo{} class Program{ static void Main(string[] args) { Dictionary foos = new Dictionary(); for(int i = 0; i < 5; i++) foos.Add("Bar1." + i, new Bar1()); for (int i = 0; i < 10; i++) foos.Add("Bar2." + i, new Bar2()); List bar2List = new List(); foreach (Foo foo in foos.Values) { if(foo is Bar2) { bar2List.Add((Bar2)foo); } } }}
Are there any other method to extract the Bar2 elements from the dictionary into the Bar2 array (bar2List) instead of using foreach-loop and if-statment?