agenthost
agenthost

Reputation: 768

Find datarows with the same id in C#

It is my first time working with Datarows or tabular data. Considering I have a simple table with two columns, one contains the ID and the other contains a name string. What I need to do is find two Datarows with the same ID, and pass these two rows to another function, lets call it HandleTheDuplicates.

At the moment I am trying store the previous ID in another variable and check if this matches to the current ID and then add it to a list of type DataRow.

List<DataRow> RowList = new List<DataRow>();
int previous = 0 ;
foreach (DataRow rowToMatch in importSetOfTables.Tables["MyTable"].Rows)
{
     int rowID = Convert.ToInt32(rowToMatch["ID"]);                               
     if (previous == rowID)
     {
          RowList.Add(rowToMatch);
     }
     else
     {
          RowList.Clear();
     }
     previous = rowID;

     if(RowList.Count > 1) //in case of a match
     {
          HandleTheDuplicates(RowList);
     }
}

I don't know if this is the right way of doing something like this or if there could be something more simpler.

Upvotes: 0

Views: 1741

Answers (2)

Scott Twombly
Scott Twombly

Reputation: 84

LINQ is a good option here:

List<DataRow> RowList = new List<DataRow>();

foreach (DataRow row in importSetOfTables.Tables["MyTable"].Rows)
{
    // Use LINQ to get a list of rows matching on ID
    List<DataRow> matches = (from t in importSetOfTables.Tables["MyTable"].Rows
                             where row.ID == t.ID
                             select a).ToList();
    // Insert matching rows into your collection
    if (matches.Count() > 0 )
         if (!(RowList.Contains(matches[0]))
             RowList.AddRange(matches);
}

If you want to remove them from the original collection, another foreach loop might work: (Generally don't want to remove items from a collection you are iterating over)

foreach(DataRow row in RowList)
{
    if (importSetOfTables.Tables["MyTable"].Rows.Contains(row))
        importSetOfTables.Tables["MyTable"].Rows.Remove(row);
}

Upvotes: 1

Steve
Steve

Reputation: 216313

Your code could work if you have the DataTable sorted by ID. To be sure then set the DataTable.DefaultView.Sort property on the ID field and then create your loop using the DataTable.DefaultView

List<DataRow> RowList = new List<DataRow>();
int previous = 0 ;
importSetOfTables.Tables["MyTable"].DefaultView.Sort = "ID";
foreach (DataRowView rw in importSetOfTables.Tables["MyTable"].DefaultView)
{
     int rowID = Convert.ToInt32(rw["ID"]);
     if (previous == rowID)
          RowList.Add(rw.Row);
     else
     {
          // Call the function that handles the duplicates
          if(RowList.Count > 1) 
             HandleTheDuplicates(RowList);
          RowList.Clear();
     }
     previous = rowID;
}

Upvotes: 1

Related Questions