如何从数据行阵列中删除数据行?

时间:2016-01-14 17:03:48

标签: c# linq datarow

我循环遍历一个数据行数组,当一个特定的随机项无效时,我想删除该项并获得新的总数以获得另一个随机项。 但是当我删除一个数据行时,数据行不会消失......是的,可能有更好的方法可以做到这一点,但我做得不够聪明......

而不是删除行,我在

中看到了这一点

ItemArray = podLps[1].ItemArray抛出了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();
   }
}

3 个答案:

答案 0 :(得分:3)

看看这个例子,它应该指出你正确的方向去除我刚刚测试过的行并且它可以工作

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);
    }
}

答案 1 :(得分:0)

最简单的方法是将DataRow[]数组转换为List,调用RemoveAt然后将列表转换回数组:

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

答案 2 :(得分:0)

我建议使用list for podLps而不是数组。 然后你可以像Jaco提到的那样使用.RemoveAt(dosn&#39; t for array)。

DataRow.Delete()只标记下次更新DataTable时要删除的行。