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
This topic was copied from this DevCurry blog by Suprotim Agarwal.
Carsten Siemens edited Revision 5. Comment: Pirated Content - see my comment
XAML guy edited Revision 4. Comment: added reference, you need to get permission for this
Ed Price - MSFT edited Revision 1. Comment: Title casing. Adding tags.
As my experience, i think if LINQ is not a solve to all problems, is so close than that. Great job!
NOTE: This article was reported as Pirated/Plagiarized Content (content you didn't write) and will be removed. Please do not steal content from others. If you feel we are mistaken, please leave a comment or email tnwiki at Microsoft with a link to this article and with clear and detailed reasons why you own the content or have explicit permission from the author.
Content was taken from: "Filter a Type in .NET inside the For-Each Loop"
Published by Suprotim Agarwal on September 20, 2010
www.devcurry.com/.../filter-type-in-net-inside-for-each-loop.html