Here’s a simple example of using LINQ to select only Strings from an ArrayList that contains both integers and strings.
C#static void Main(string[] args) { ArrayList al = new ArrayList { "Hello", 200, "World", false, 100 }; var onlyStr = al.OfType<string>(); Console.WriteLine("Printing Only Strings"); foreach(var str in onlyStr) Console.WriteLine(str); Console.ReadLine(); }VB.NET
Sub Main(ByVal args() As String) Dim al As ArrayList = New ArrayList From {"Hello", 200, "Word", False, 100} Dim onlyStr = al.OfType(Of String)() Console.WriteLine("Printing Only Strings") For Each str In onlyStr Console.WriteLine(str) Next str Console.ReadLine() End SubAs you can see, we are using the Enumerable.OfType<TResult> Method which filters the elements of an IEnumerable based on a specified type, in our case the String type.
OUTPUT
No comments:
Post a Comment