May 17, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Using LINQ to select Only Strings from an ArrayList"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions