This question already has answers here:
Possible to iterate backwards through a foreach?
(13 answers)
Closed 7 years ago.
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++).
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--)
// ...
Related
This question already has answers here:
How to remove elements from a generic list while iterating over it?
(28 answers)
Closed 5 months ago.
The code only removes duplicates apart from the last 2 of any number
for (int i = 0; i < primeNumbers.Count; i = i + 1)
{
for (int j = i + 1; j < primeNumbers.Count; j = j + 1)
{
if (primeNumbers[i] == primeNumbers[j])
{
primeNumbers.RemoveAt(j);
}
}
}
for (int i = 0; i < primeNumbers.Count; i++)
Console.WriteLine(primeNumbers[i]);
To improve time complexity, use a Set. A Set cannot have duplicates. Just iterate once through your list, and add each value to the set.
Complexity will be linear O(n).
Your inner for loop will skip the next entry after the remove. After the remove, decrement j so that it will recheck the current entry on the next loop.
So add j--;
this is simple and elegant:
const noDupes = primeNumbers.filter((item, ind, arr) => ind === arr.indexOf(item));
HTH
I would use the following code to improve:
If your primeNumbers is an Array[]:
primeNumbers = primeNumbers.Distinct().ToArray();
If your primeNumbers is an List<>:
primeNumbers = primeNumbers.Distinct().ToList();
If your primeNumbers is an HashSet<>:
primeNumbers = primeNumbers.Distinct().ToHashSet();
EXTRA
When filling up your list of primenumbers, use HashSet
HashSet primeNumbers = new();
primeNumbers.Add(number);
It will automatically remove the duplicates.
This collection is introduced in . NET 3.5.
This question already has answers here:
Is there an easy way to return a string repeated X number of times?
(21 answers)
Closed 2 years ago.
How can I increment stars in a do while loop not for loop.
Output should be :
*
**
***
****
How to assign i to "*" in following
do
{
Console.WriteLine("{i}", i);
i++;
} while (i <= 10);
If you are looking to write a number of "asterixis" on a single line based on a do-while. A simple solution would be:
int i = 0;
do
{
Console.WriteLine(new String('*', i));
i++;
} while (i <= 10);
Although I may not be understanding your question
This question already has answers here:
Variables in a loop
(9 answers)
Loop through object variables with different number on the name [duplicate]
(5 answers)
Iteration with variable name [duplicate]
(1 answer)
Closed 2 years ago.
I am trying to use a for loop to iterate through a series of variable names each ending in a number from 1 to 10. I have seen a few other answers to this question but have been unable to make any work for my specific situation. My code is as follows:
string cat2Pos0 = cat2[0];
int numOfPos0 = cat2.Where(x => x.Equals(cat2Pos0)).Count();
List<int> indexOfPos0 = new List<int>();
bool check = cat2.Contains(cat2Pos0);
int index = 0;
if (check == true)
{
for (int i = 0; i < numOfPos0; i++)
{
index = cat2.FindIndex(x => x == cat2Pos0);
indexOfPos0.Add(cat2.IndexOf(cat2Pos0));
}
}
else if (cat2Pos0 == "-")
{
numOfPos0 = 17;
}
I need to loop through 10 variables names cat1 - cat10. In the code: whenever there is the phrase "cat" I need to be able to adjust it depending on a for loop e.g. cat1 or cat5:
string cat3pos0 = cat3[0];
or:
index = cat3.FindIndex(x => x == cat3Pos0);
Unfortuantely, I am unable to simply write out each variation individually as that would use up almost 3700 lines of code and I was hoping that there would be a better way of achieveing this.
Many thanks, all help is greatly appreciated,
Josh
See here how to use reflection for this. (something like this.GetType().GetField("cat" + i.ToString());.)
But I would really suggest changing your variables to one array of 10 variables. So cat will be an array of arrays (since your cat's seem to be arrays).
This question already has answers here:
List<> Capacity returns more items than added
(5 answers)
Closed 7 years ago.
Would anybody help me to understand what is wrong with this for loop why am I getting out of boundaries exception please?
Capacity of this particular list is set to 8.
public static List<Beds> BedsList = new List<Beds>(8);
private int GetFirstAvailableBed()
{
var result = 0;
for (int i = 0; i < Beds.BedsList.Capacity; i++)
{
if (Beds.BedsList[i] == null) // Here is trhowing the exception
{
result = i;
break;
}
}
return result;
}
Use List.Count instead of List.Capacity.
The Capacity property
Gets or sets the total number of elements the internal data structure can hold without resizing.
It's not the number of items in the list.
You should use List#Count
for (int i = 0; i < Beds.BedsList.Count; i++)
This question already has answers here:
Intelligent way of removing items from a List<T> while enumerating in C#
(11 answers)
How to remove elements from a generic list while iterating over it?
(28 answers)
Closed 7 years ago.
If I use an item in a foreach loop and I can't use the item it has to delete the item that is currently in the foreach loop.
This is the code that I have right now:
foreach (Line line in linelijst)
{
try
{
if (line.ActorIndex() == 0)
{
line.setStartPoint(actorenlijst[0].getLinePoint()); //if actorenlijst[0] doesn't excist it has to delete the current line
}
if (line.ActorIndex() == 1)
{
line.setStartPoint(actorenlijst[1].getLinePoint()); //if actorenlijst[1] doesn't excist it has to delete the current line
}
if (line.ActorIndex() == 2)
{
line.setStartPoint(actorenlijst[2].getLinePoint()); //if actorenlijst[2] doesn't excist it has to delete the current line
}
Point start = line.getStartPoint();
Point end = line.getEndPoint();
Pen lijn = new Pen(Color.Black, 1);
graphics.DrawLine(lijn, start, end);
}
catch
{
//delete current line from the list
}
}
Thanks for your interest to help other people :)
Try just creating another temporary list for the items that need to be deleted then when your done looping you can just delete the ones in the temp list.
List<Type> temp = new List<Type>()
foreach(item in mainList)
{
if (item.Delete)
{
temp.Add(item);
}
}
foreach (var item in temp)
{
mainList.Remove(item);
}
You canNOT change the listing through which you are going.
It is locked because it is an Enumeration as long as it is in the foreach.
So use a for-loop instead.
for (int i = linelijst.count; i > 0; i--)
{
// linelijst[i - 1] can be removed, etc.
}
or use (as the commentators suggested):
for (int i = linelijst.count - 1; i >= 0; i--)
{
// linelijst[i] can be removed, etc.
}