Home >Backend Development >C++ >Is There a Shorter Way to Cast a List to a List in C#?
Shorter Syntax for Casting from a List
Casting a list of items from one type to another can often be achieved using the following approach:
List<Y> ListOfY = new List<Y>(); foreach (X x in ListOfX) ListOfY.Add((Y)x);
However, this method requires casting each item individually, which can be cumbersome. Is there not a more concise way to cast the entire list in one step?
Answer
Yes, the Cast<> extension method in the System.Linq namespace provides a concise syntax for casting a list. Here's how you can use it:
List<Y> listOfY = listOfX.Cast<Y>().ToList();
Keep in mind the following points:
The above is the detailed content of Is There a Shorter Way to Cast a List to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!