Friday, September 5, 2008

Using LINQ To Ensure No Objects Have Duplicate Keys

I had an interseting business requirement the other day. I'm working with a CSLA Collection of objects, and they wanted the end user to be able to be able to change a property that is one of the three columns that makes up the primary key. I sat down and started using some LINQ to objects and was amazed at how much power it has in just a 6 lines of code. It was also my first time using the Group By Function

Normally with the group by, you perform some agregate functions on the group. So the "Into Group" would be "Into Sum(naviagation.SectDeNavOrdrNbr)". But by Grouping it into group, the result is a collection that contains the objects in the Group By Clause (SectDeNavOrdNbr, SectName, DeName) and then a collection of all the objects that are in that group.

So after I have my group by clause, I perform a contains to see if any collections of the group have more than one item in them. The must amazing part, is techinally, it only took 1 line of code! In the words of a dear friend of mine, "God Bless .Net".




Dim hasDuplicatePrimaryKeys As Boolean = ( _
From navigation As SectionDataElementNavigationReference In Me _
Group By navigation.SectDeNavOrdNbr, navigation.SectName, navigation.DeName _
Into Group).Contains(Function(c) c.Group.Count() > 1)

If (hasDuplicatePrimaryKeys) Then
Throw New InvalidConstraintException("More than one Section Data Element Navigation Reference was found with the same Section Name, Data Element Name, and Section Data Element Navigation Order Number")
End If






No comments: