0

I'm developing on a more or less legacy C# application and stumbled upon a code that I wrote some time ago. But somehow I get the feeling, that this is not really a good approach to this.

How would I make this code better?

        public static void RemoveEntries(DataTable source, ref DataTable destination, int indexSource, int indexDestination)
    {
        var arVals = new int[source.Rows.Count];
        var i = 0;
        foreach (DataRow sourceRow in source.Rows)
        {
            if (sourceRow.RowState != DataRowState.Deleted)
                arVals.SetValue(sourceRow[indexSource], i);
            i += 1;
        }

        foreach (
            var destinationRow in 
            from DataRow row3 
                in destination.Rows 
            where arVals.Contains((int) row3[indexDestination]) 
            where row3.RowState != DataRowState.Deleted 
            select row3
        )
            destinationRow.Delete();
    }

Thanks in advance, bb

3
  • Instead of using arVals, can't you just delete the rows in the first loop? Is there some sort of Primary Key field that would uniquely identify a row that exists in both tables? Commented May 23, 2013 at 13:03
  • "code better" meaning less code or performance? Commented May 23, 2013 at 13:12
  • "Better code" meaning less code that is more understandable. I'm not really sure why I even need 2 DataTables.. Commented May 24, 2013 at 7:18

1 Answer 1

1
public static void RemoveEntries(
    DataTable source, int sourceIndex,
    DataTable destination, int destinationIndex) {
    var query=
        from DataRow rowDestination in destination.Rows
        where rowDestination.RowState!=DataRowState.Deleted
        from DataRow rowSource in source.Rows
        where rowSource.RowState!=DataRowState.Deleted
        where rowSource[sourceIndex]==rowDestination[destinationIndex]
        select rowDestination;

    foreach(var row in query.ToArray())
        row.Delete();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.