September 20, 2010

Filter a Type in .NET inside the For-Each Loop




Here’s a nice way to filter an ArrayList right inside the For-Each Loop. We have to filter and print only ‘integers’ greater than 10.

static void Main(string[] args)
{
ArrayList arr = new ArrayList();
arr.Add(15);
arr.Add(25.35);
arr.Add(10);
arr.Add(20);
arr.Add(25);
arr.Add(20.2);

foreach (var num in arr.OfType<int>().Where(x => x > 10))
{
Console.WriteLine(num);
}

Console.ReadLine();
}

As you can observe, we are using the Enumerable.OfType<TResult> inside the foreach loop to filter only those elements of the ArrayList which are integers and greater than 10. This code will only work in .NET 3.5 and above.

OUTPUT

image



'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 "Filter a Type in .NET inside the For-Each Loop"
 

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