DennyDotNet

Awesome ASP.NET C# and other cool coding stuff

About the author

Denny Ferrassoli
Developer at Casting Networks. MCP / .NET
E-mail me Send mail
Add to Technorati Favorites

Recent posts

Recent comments

Authors

Categories

None


Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

LINQ and Enumerable.Cast

I've been using LINQ lately and I've been having a lot of fun with it. It makes working with collections so much better! Many thanks to "Pro LINQ by Joseph C. Rattz" (Amazon) - a great book to get you started on LINQ.

So I ran into a bit of a snafu yesterday and thought I would share some cool LINQ methods.

I was working on a Windows App and using a DataGridView to keep track of some information. I wanted to quickly search through the rows and determine if a rows "filename" column was already in the list. Naturally I wanted to "LINQafy" everything to get it done in one line of code. I quickly ran into the issue that DataGridView.Rows is a DataGridViewRowCollection so I couldn't use IQueryable<DataGridViewRow> because "Source is not IEnumerable<>"

So after a short time playing with DataGridView.Rows.AsQueryable() and also getting nowhere I noticed the Cast extension method. From there it was pretty easy to come up with a solution by reading the method signature:


DataGridViewRow dgvrow = grid.Rows.Cast<DataGridViewRow>().Where(r => r.Cells["filename"].Value.ToString() == filename).SingleOrDefault();

Now I have a reference to the DataGridViewRow (or null if it doesn't exist). It's very useful that using the Cast method will create an IEnumerable<T> so that you can easily do all your LINQ queries.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:
Posted by Denny on Monday, January 14, 2008 4:39 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Comments

Comments are closed