// Map set of anonymous objects to an Array object.
// Here were are relying on type inference of the generic
// type parameter, as we don't know the type of type!
return makesColors.ToArray();
}
we could invoke and process the data from Main() as follows:
Array objs = GetProjectedSubset();
foreach (object o in objs)
{
Console.WriteLine(o); // Calls ToString() on each anonymous object.
}
Note that we have to use a literal System.Array object and cannot make use of the C# array
declaration syntax, given that we don’t know the underlying type of type! Also note that we are not
specifying the type parameter to the generic ToArray() method, as we (once again) don’t know
the underlying data type until compile time (which is too late for our purposes).
The obvious problem is that we lose any strong typing, as each item in the Array object is
assumed to be of type Object. Nevertheless, when you need to return a LINQ result set which is the
result of a projection operation, transforming the data into an Array type (or another suitable con-
tainer via other members of the Enumerable type) is mandatory.
Do'stlaringiz bilan baham: |