Sunday, May 4, 2008

CheckBoxList, Linq, and XML

I’ve been playing around with the new Linq stuff in .NET 3. I’m finding it’s possible to do things much easier with Linq, as well as with significantly less code. Recently I had to take all the selected items in an asp.net checkbox list (cblOpinion) and write them to an XML file (filePath). The code turned out to be a single statement:

new XElement("Opinions",
cblOpinion.Items.OfType()
.Where(o => o.Selected)
.Select(o => new XElement("Opinion", o.Text)))
.Save(filePath);

This created a nice XML file that looked like:



opinion a...
opinion b...
opinion c...
opinion d...


Pretty nifty!

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...