0

If I have list of data, I want delete separate rows (not bulk delete) with a loop.

Here my Code

var objecctCount = listItemsDelete.Count;
for (int i = objecctCount; i > 0; i--)
{
    listItemsDelete[i].DeleteObject();
    spDataContext.ExecuteQuery();
}

where,

  • listItemsDelete is list of data,
  • listItemsDelete[i].DeleteObject(); delete separate row from listItemsDelete,
  • spDataContext.ExecuteQuery(); is helps update values to the listItemsDelete

My logic is working good. my question is, Is it possible to change the for-loop to foreach with negative statement? Because my knowledge about foreach is helps to work with positive statement(I++).

  • Can you convert my code to foreach code? –  Feb 10 '16 at 10:56
  • 1
    Does `listItemsDelete[i].DeleteObject();` remove it from listItemsDelete? Because if you use `foreach` then you can't alter the collection you are looping through. – Mark Feb 10 '16 at 11:01

1 Answers1

0

So you want to reverse the loop?

foreach(var obj in listItemsDelete.Reverse())
{
    obj.DeleteObject();
    spDataContext.ExecuteQuery();
}

Since you are using .NET 2 you can't use LINQ. Stay with your for-loop but fix following error.

Instead of

for (int i = objecctCount; i > 0; i--)
// ...

use this:

for (int i = objecctCount - 1; i >= 0; i--)
// ...
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • But i can't Call the `Reverse()` function –  Feb 10 '16 at 11:01
  • Add `using System.Linq` to the top of your code file. [`Enumerable.Reverse`](https://msdn.microsoft.com/library/bb358497(v=vs.100).aspx) is a LINQ extension method. What is `listItemsDelete` at all? – Tim Schmelter Feb 10 '16 at 11:02
  • Am using asp.net 2.0. Is it okay? –  Feb 10 '16 at 11:06
  • Also saying specify method does not support –  Feb 10 '16 at 11:10
  • @DotNetDeveloper: LINQ is new in .net 3.5. You should use your for-loop. But fix the error, use `for(int i = objecctCount - 1; i >= 0; i--)` instead. – Tim Schmelter Feb 10 '16 at 11:15
  • Yes, Your last comment was worked, Just I changed it. thanks –  Feb 10 '16 at 11:19