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.


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)


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
Next str
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.


LINQ ofType

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: