问题
What is the proper use of ConverAll ? Will it convert one type to another type?
like
List<int> intList = new List<int>();
intList.Add(10);
intList.Add(20);
intList.Add(30);
intList.Add(33);
var query= intList.ConvertAll(x=>(double)x);
for this i can use cast or OfType<>.
回答1:
ConvertAll isn't an extension method, it's a real method on List<T>
itself.
It returns a new list containing the converted elements. So in your example, the query
variable isn't actually a query, it's a List<double>
.
Cast and OfType are extension methods that operate on IEnumerable
and return an IEnumerable<T>
. However they're not suitable for your stated purpose: Cast
can convert reference types but cannot convert value types, only unbox them. OfType
doesn't perform any conversion, it just returns any elements that are already of the specified type.
回答2:
ConvertAll will just call your delegate/anonymous method for each element of the list. What this does is entirely up to you.
In the example code you posted, it will attempt to cast each element to a double and return that, which means you'll get a List<Double>
in return.
You should not use OfType<T>
, since this will filter the elements based on the type, and will only return a different type than the original if it is type compatible due to inheritance or interface implementation.
In other words, .OfType<Double>
will return no elements, since none of the ints are also doubles.
回答3:
ConvertAll
is a projection operator and maps most closely to LINQ's Select
. LINQ's Cast
is a specific projection operator and represents doing what you did [via projection] - or it would (as pointed out in Luke's answer [and comment], which I +1'd) if you weren't converting to a value type.
In general, LINQ has a more complete and well-thought-through set of operators, which makes older stuff like ConvertAll
look a bit silly at times [like this]. (or @stoopid :D).
回答4:
to my knowledge, OfType<T>
will only return the elements in the collection that are of the specified type T.
ConvertAll allows you to convert the elements to another type.
来源:https://stackoverflow.com/questions/1913955/extension-method-convertall