In this post, we’ll take a straight forward procedure based set of code and convert it to LINQ using a ReSharper from JetBrains suggestion. I’ve found that in general, when I do things with foreach syntax, there is often a better way in Linq to do this. The better does not jump out at me sometimes, however with ReSharper, it is often a button click away.
The initial code is as follows:
int selectedIndex = 0; foreach (var rec in codeCampStringDictionary) { if (rec.Key == codeCampYear) { break; } selectedIndex++; }
And, ReSharper is going to suggest turning it into:
int selectedIndex = codeCampStringDictionary.TakeWhile(rec => rec.Key != codeCampYear).Count();
Simply Amazing! TakeWhile had not even occurred to me.
(All while getting the Silicon Valley Code Camp Site Ready for our V5 Event, October 9th and 10th, 2010)
So, to explain the problem a little better, on the Silicon Valley Code Camp web site (which, by the way is scheduled for October 9th and 10th, 2010 this year), we have an ASP.NET DropDownList in the upper right hand corner that the user can switch between different years. That is, say they want to see all the sessions in 2008’s code camp, they can simply change the dropdown and the site completely updates. When they do this, we don’t want to re-read the data table that contains the code camp years, we simply want to process the data that has already been stored in the ViewState of the DropDownList and use that to figure out the key value of the table entry for the code camp year they selected.
OK, if you didn’t follow all that, it really doesn’t matter. This blog post is simply about how clever ReSharper is and how much I enjoy what the tool does. It’s nice to have a tool teach me things!
The complete commented code is below that includes some comments about how it actually works. I’m looking forward to several people posting comments letting me know that there is even a simpler way to do this. I love my job!
// Create a dictionary out of values in a DropDownList. That is,
// the DropDownList has a Key Value which is it's primary key
// and a text value which is the Code Camp Year.
Dictionary<int, string> codeCampStringDictionary =
DropDownListCodeCampYearID.Items.Cast<ListItem>().
OrderBy(a => a.Value).
ToDictionary(itemdd => Convert.ToInt32(itemdd.Value),
itemdd => itemdd.Text);
// Then, loop through the values in the dictionary and figure out
// the offset of a particular value. That is, if there are 3 values
// in the list of 2008,2009,2010 which have primary keys of 3,4,5
// we want to know, that given codeCampYear is 4, then selectedIndex
// is the second value and should be 2.
int selectedIndex = codeCampStringDictionary.TakeWhile
(rec => rec.Key != codeCampYear).Count();
string dateString = Utils.GetCodeCampDateStringByCodeCampYearId(codeCampYear);
DropDownListCodeCampYearID.SelectedIndex = selectedIndex;
HeaderId1.Text = String.Format("Saturday and Sunday, {0}", dateString);
Let the comments roll!