1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| static readonly IDictionary<Type, Func<A, int>> mapping = new Dictionary<Type, Func<A, int>>
{
{ typeof(B), a => ((B)a).Value },
{ typeof(C), a => ((C)a).Value },
{ typeof(D), a => ((D)a).Value }
};
static IList<int> GetValues(IList<A> listOfA)
{
return listOfA.Select(mapping[listOfA.First().GetType()]).ToList();
}
static void TestListOfA()
{
IList<A> bs = new[]{ new B { Value = 1 }, new B { Value = 2 }, new B { Value = 3 } };
IList<A> cs = new[]{ new C { Value = 4 }, new C { Value = 5 }, new C { Value = 6 } };
IList<A> ds = new[]{ new D { Value = 7 }, new D { Value = 8 }, new D { Value = 9 } };
IList<int> bValues = GetValues(bs);
IList<int> cValues = GetValues(cs);
IList<int> dValues = GetValues(ds);
foreach (int bValue in bValues) Console.Write(bValue + " ");
Console.WriteLine();
foreach (int cValue in cValues) Console.Write(cValue + " ");
Console.WriteLine();
foreach (int dValue in dValues) Console.Write(dValue + " ");
Console.WriteLine();
} |
Partager