Denny.NET

I can haz ASP.NET goodness?

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

Disclaimer

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

© Copyright 2008

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:

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

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

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:
Categories: ASP.NET | Server-Side
Posted by Denny on Monday, January 14, 2008 9:39 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Comments

john mertus us

Thursday, September 11, 2008 2:34 PM

john mertus

you don't have to go to such great lengths,
just define the type of the variable; e.g.,

var j = from DataGridViewRow c in grid.Rows
where ...
select ...


Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading