punkouter
punkouter

Reputation: 5366

How do I delete a datarow from a datarow array?

I am looping through a array of datarows and when a particular random item is not valid I want to remove that item and get the new total to get another random item. But when I delete a datarow the datarow does not go away... And yes there is probably a much better way to do this but I am not smart enough to do it..

Instead of removing the row I see this inside

ItemArray = podLps[1].ItemArray threw an exception of type System.Data.RowNotInTableException

//PHASE 1: Get all LPs in the pod and add to collection
List<DataRow> allLps = dtLp.AsEnumerable().ToList();
DataRow[] podLps = allLps.Where(x => x.ItemArray[0].ToString() == loPod).ToArray();

//PHASE 2: Pick a random LP from collection that has valid WAVE1
for (int i = podLps.Count(); i > 0; i--)
{
   //Recount items in collection since one may have been removed
   int randomIndex = random.Next(podLps.Count());
   var randomLpUserId = podLps[randomIndex].ItemArray[1].ToString();
   var randomLpWave1 = int.Parse(podLps[randomIndex].ItemArray[2].ToString());

   //Get WAVE1 # for selected LP
   lpNumberOfLoans = GetNumberOfLoans(session, randomLpUserId);

  //check if LP has valid WAVE1 then use this person
   if (randomLpWave1 > lpNumberOfLoans)
   {
       return randomLpUserId;
   }
   else
   {
       podLps[randomIndex].Delete();
   }
}

Upvotes: 1

Views: 3923

Answers (3)

Alex
Alex

Reputation: 21766

The easiest method is to convert your array of DataRow[] to a List, call RemoveAt and then convert the list back to an array:

 var dest = new List<>(podLps);
 dest.RemoveAt(randomIndex);
 podLps = dest.ToArray();

Upvotes: 0

MethodMan
MethodMan

Reputation: 18843

look at this example and it should point you in the right direction for removing rows I just tested it and it works

for (int i = myDataTable.Rows.Count - 1; i >= 0; i--)
{
    DataRow row = myDataTable.Rows[i];  //Remove
    if (myDataTable.Rows[i][0].ToString() == string.Empty)
    {
        myDataTable.Rows.Remove(row);
    }
}

Upvotes: 4

Bashn
Bashn

Reputation: 314

I would suggest to use a List for podLps instead of an array. Then you can use .RemoveAt as Jaco mentioned (dosn't work for arrays).

DataRow.Delete() just flags the Row to be deleted in the next update of your DataTable.

Upvotes: 0

Related Questions