How to Convert a Collection From One Type to Another Type Using LINQ Cast
Typically we have the problem of having a collection of objects which we would like to convert into another type of collection (for example, from an ArrayList to a List<>). If the collection inherits from IENumerable or IQueryable (List<> for example), we can use LINQ's ConvertAll. However, if the collection instead inherits from System.Collections (ArrayList and Dictionary for example), we need to use LINQ's Cast extension.
Microsoft Explanation:
Converts the elements of an IEnumerable to the
specified type.
NOTE: LINQ Cast uses deferred execution. I will be using LINQ ToList to force immediate execution.
This method is implemented by using deferred execution. The immediate return
value is an object that stores all the information that is required to perform
the action. The query represented by this method is not executed until the
object is enumerated either by calling its GetEnumerator method directly
or by using foreach in Visual C# or For Each in Visual Basic.
Let's take the example of converting an ArrayList to a List.
Converting an ArrayList to a List<> Using C# 2.0
// holds the final list
List<int> SampleIntList = new List<int>();// a list of integers, in string format
ArrayList SampleStringList = new ArrayList() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };// convert the list to an int list
foreach (string item in SampleStringList)
SampleIntList.Add(Convert.ToInt32(item));// output the result
foreach (int item in SampleIntList)
Console.WriteLine(item.ToString());/*
* Output:
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
* 10
*/
This is pretty straight-forward. If the types had been more complex, though, you could have seen more work being done in the first foreach loop. Using LINQ, we can call Cast, and using a Lambda expression, convert the entire collection in one line of code:
Convert an ArrayList to a List<> Using LINQ Cast
// holds the final list
List<int> SampleIntList = new List<int>();// a list of integers, in string format
ArrayList SampleStringList = new ArrayList() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };// convert the list using Cast
SampleIntList = SampleStringList.Cast<int>().Select(x => Convert.ToInt32(x)).ToList();// output the result
foreach (int item in SampleIntList)
Console.WriteLine(item.ToString());/*
* Output:
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
* 10
*/
Notice that we cannot use a Lambda expression directly in the Cast<>() fuction, we have to call Select() (or another LINQ selector). Also notice the use of ToList as the final function call, to force the immediate conversion of the list.
For more complex data types, using LINQ Cast can be a very efficient way to convert a collection into a List or other IENumerable type.
If have questions, comments, or suggestion, please feel to post them in the LINQ Exchange Forum
loading...
loading...
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
