Type conversion in LINQ: Detailed explanation of Cast() and OfType() methods
LINQ (Language Integrated Query) is a powerful tool in the .NET framework that allows developers to query and transform data using familiar syntax. When you need to convert elements in ArrayList to IEnumerable
Cast() method
The Cast() method is used to explicitly convert all elements in the ArrayList to the specified type. It attempts to cast each element to the target type, regardless of its actual type. If any element fails to be cast, an InvalidCastException is thrown.
OfType() method
TheOfType() method selectively converts only those elements that can be safely converted to the target type. It returns an IEnumerable
Applicable scenarios for Cast() and OfType() methods
Choosing Cast() or OfType() depends on your specific needs:
Using Cast():
Using OfType():
Example
Suppose you have an ArrayList containing strings and integers:
<code class="language-csharp">object[] objs = new object[] { "12345", 12 };</code>
Use Cast():
<code class="language-csharp"> try { string[] strArr = objs.Cast<string>().ToArray(); } catch (InvalidCastException) { // 处理异常 }</code>
In this case, Cast() will try to convert both elements to strings. Since one of them is an integer, an InvalidCastException is thrown.
Use OfType():
<code class="language-csharp"> string[] strArr = objs.OfType<string>().ToArray(); // 只包含 "12345"</code>
OfType() will successfully retrieve string elements from the ArrayList and exclude integer elements.
By understanding the difference between Cast() and OfType(), you can effectively convert types and filter data when using LINQ, ensuring the accuracy and reliability of queries.
The above is the detailed content of Cast() vs. OfType() in LINQ: When Should I Use Each for Type Conversion?. For more information, please follow other related articles on the PHP Chinese website!