Checking for violation of primary key in a DataTable I coded this function to check for a violation of a primary key in a DataTable. The main idea is to retrieve a list of every row that the same value of the column in input and set an error to it.

Private Sub PrimaryKeyCheck(Of ColumnType)(dt As DataTable, ColumnName As String)

    Dim violatingGroups =
        dt.AsEnumerable() _
        .Where(Function(i) i.RowState &lt;&gt; DataRowState.Deleted) _
        .GroupBy(Function(i) i.Field(Of ColumnType)(ColumnName)) _
        .Where(Function(g) g.Count() &gt; 1).ToList()

    For Each violatingGroup In violatingGroups
        For Each violatingRow In violatingGroup
            violatingRow.SetColumnError(ColumnName, "Error, Violating PK") ' TODO Traduzione
        Next
    Next

End Sub


I'm a newbie of Linq, so I'm asking. Is it possible to improve this function in terms of performance and correctness? Is it possible to remove the double for each?
According to the .NET Naming Guidelines, parameter names should be written in lower Camel case and be descriptive.

Private Sub PrimaryKeyCheck(Of ColumnType)(table As DataTable, columnName As String)



  "Is it possible to remove the double for each?"


Yes! There's a handy method in the List&lt;T&gt; class named ForEach.  The provided action will be invoked for each element in the list.

I advice you to not use the name i in this context as this name is widely used as an abbreviation for index (usually a number). A better name is r or row. And g could be renamed to group.

You should also move the magic string "Error, Violating PK" to a constant.

Const errorMessage As String = "Error, Violating PK"

table _
    .AsEnumerable() _
    .Where(Function(r) r.RowState &lt;&gt; DataRowState.Deleted) _
    .GroupBy(Function(r) r.Field(Of ColumnType)(columnName)) _
    .Where(Function(g) g.Count() &gt; 1) _
    .ToList() _
    .ForEach(Sub(g) g.ToList().ForEach(Sub(r) r.SetColumnError(columnName, errorMessage)))