Using LINQ to select Only Strings from an ArrayList

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 Sub

As 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

LINQ ofType






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: