Rodney
Rodney

Reputation: 5565

How to remove records from a dataset with LINQ

I have a dataset (called dataSet below) with a single table and some records in it. One of the columns is called Message and contains an error message. If any records have a value in this field I want to copy it into an error dataset (errorDataSet below) and then remove it from the original dataset. I managed to get this far with LINQ:

        DataSet errorDataSet = dataSet.Copy();

        //find all records that have a Message column value
        var query = from row in errorDataSet.Tables[0].AsEnumerable()
                    where !String.IsNullOrEmpty(row.Field<string>("Message"))
                    select row;

        DataSet tempErrorDataSet = errorDataSet.Clone();
        foreach (var row in query)
        {
            tempErrorDataSet.Tables[0].Clear();
            tempErrorDataSet.Tables[0].ImportRow(row);
            utility.WriteError(connectorName, row["Message"].ToString(), tempErrorDataSet);

            //remove the error row from the good data
            dataSet.Tables[0].Rows.Remove(row);
        }

The bottom line throws an exception or I get errors regarding modifying a collection etc. I'm sure there is a simple way of doing this in LINQ.

Note: The reason I have tempErrorDataSet is that I convert it to XML and pass it into a stored proc - it only takes a record at a time in that format, hence I clear it each time.

Upvotes: 2

Views: 974

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134881

Your query is enumerating (indirectly) through the rows in the table. As you should already know, you cannot modify a collection (remove something in this case) as you enumerate over it. Throw the contents into a list beforehand. That way you're not enumerating through the actual table but a copy of some rows.

var query = (from row in errorDataSet.Tables[0].AsEnumerable()
             where !String.IsNullOrEmpty(row.Field<string>("Message"))
             select row).ToList();

Upvotes: 3

Related Questions