Keep last N items and remove other items from ListBox - c#

I have a C# Winform with a ListBox. I am trying to remove all the items except the last 5 items. The ListBox sort is set to Ascending.
The items in the ListBox look like the following:
2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28
Here is my code to remove the beginning items.
for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
try
{
HomeTeamListBox.Items.RemoveAt(i);
}
catch { }
}
I've also tried HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);

While there are more than n items in the list, you should remove items from start of the list.
This way you can keep the last n items of ListBox:
var n = 5;
while (listBox1.Items.Count > n)
{
listBox1.Items.RemoveAt(0);
}

Your index i is going to increase by one each time it loops, but you are going to be removing an element each time you loop. What you want to do is remove each element at index 0 for the first 5 passes. So using your current For Loop
HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[0]);
Is what you want in the body.

This should work for you;
if(HomeTeamListBox.Items.Count > 5)
{
var lastIndex = HomeTeamListBox.Items.Count - 5;
for(int i=0; i < lastIndex; i++)
{
HomeTeamListBox.Items.RemoveAt(i);
}
}

for(int i = HomeTeamListBox.Items.Count-5; i>=0; i--)
{
HomeTeamListBox.Items.RemoveAt(i);
}

Related

Which is the correct method of outputting numbers, based on the count of strings in a list<>

I am trying to loop through a collection, to get the total count of items, and
append the numbers to each item.
So for instance, there is two items in my collection.
#QuizItem.QuitTitle holds two strings, what i am trying to achieve is
Loop through the collecion, outputting the amount of items...
i.e
Music
English
My Code -
#foreach (var QuizItem in QuizDetails)
{
#for (int i = 1; i < indexCount; i++)
{
indexCount = i;
{
<p style="font-weight:bolder">#indexCount #QuizItem.QuizTitle</p>
}
}
And in OnInitialized() method
indexCount = QuizDetails.Count();
The above brings back no results..
If i take out the forloop i get my questions presented.. But obviously the
count is showing 2 on both questions...
Example below
I have tried many of different ways, but to no avail. I just would like for it to say 1 and 2 respectively by the titles, instead of 2 and 2.
Can anybody help?
You should use a foreach loop instead of a for loop, it tends to work much better in Blazor. If you need a counter, a scoped variable that you ++ in the body of the loop will serve
I solved my issue anyway, hopefully it may help, some one in the future.
#foreach (var QuizItem in QuizDetails)
{
#for (int i = 0; i <= indexCount; i++)
{
//indexCount = i;
if (i == 0)
{
i++;
if (temp == 0)
{
temp = i;
}
#for (int b = temp; b <= indexCount; b++ )
{
{
<p style="font-weight:bolder">#b #QuizItem.QuizTitle</p>
if (temp <= indexCount)
{
temp++;
break;
}
}
}
}
}
temp is a int value, that i initialize at 0..

listboxes passing values from each other

I'm trying to multiply the values of 2 listboxes together and make their product appear at another list box I'm getting the results I need but the problem is when I rerun the loop using a command button the listbox removes the next instance of the first value calculated by ppc[i] * qty[i] but when I try to remove the the listBox4.Items.Remove(ppc[i] * qty[i]) it reprints the whole array again from first element to last element
string myString = textBox1.Text.ToString();
int index = listBox6.FindString(myString, -1);
int[] qty = new int[99];
int[] ppc = new int[99];
int[] gt1 = new int[99];
listBox3.Items.Add(listBox5.Items[index]);
listBox1.Items.Add(textBox2.Text.ToString());
if (index != -1)
{
listBox6.SetSelected(index, true);
listBox2.Items.Add(textBox1.Text); //name
}
listBox3.Items.Add(listBox5.Items[index]);
listBox3.Items.Remove(listBox5.Items[index]);
for (int i = 0; i != listBox2.Items.Count ; i++)
{
ppc[i] = Convert.ToInt32(listBox3.Items[i]);
qty[i] = Convert.ToInt32(listBox1.Items[i]);
listBox4.Items.Remove(ppc[i] * qty[i]);
listBox4.Items.Add((ppc[i] * qty[i]));
}
My understanding is that this loop works once, and then when it is re-run it is out of order. Are you making sure to clear listbox4 each time this loop is executed? Also since listBox2 isn't used, it is probably better not to use it for your loop bounds.
if(listBox1.Items.Count == listBox3.Items.Count)
{
int rowCount = listBox1.Items.Count;
listBox4.Items.Clear();
for (int i=0; i < rowCount; i++)
{
ppc[i] = Convert.ToInt32(listBox3.Items[i]);
qty[i] = Convert.ToInt32(listBox1.Items[i]);
listBox4.Items.Insert(i , (ppc[i] * qty[i]));
}
}

Foreach loop with dynamic index

In my if-statement i increase the value for counter. I use var counter as the index for subcategories. After the if statement it jumps out from my loop. I would like it to begin looping subcategories[1] or [2] etc. How can i continue looping index 1, 2, 3 for my subcategories list?
int counter = 0;
int eachCounter = 0;
foreach (var item in filteredList[0].subcategories[counter].questionanswer)
{
int questionsCounter = filteredList[0].subcategories[counter].questionanswer.Count;
eachCounter++;
if (eachCounter.Equals(questionsCounter))
{
counter++;
eachCounter = 0;
}
}
Just use a for, since this isn't going to work. The foreach will iterate over the initial questionanswer on the first iteration, it won't go further on the next one.
for (int counter = 0; counter < filteredList[0].subcategories.Count; counter++)
{
var item = filteredList[0].subcategories[counter].questionanswer;
}
If you want to iterate over both lists (the inner and the outer list), use two foreach statements or for loops.
Use for each to loop through filteredList[0].subcategories array this way:
int counter = 0;
int eachCounter = 0;
foreach (var item in filteredList[0].subcategories)
{
// item is filteredList[0].subcategories[0], filteredList[0].subcategories[1] and so on.
int questionsCounter = item.questionanswer.Count;
eachCounter++;
if (eachCounter.Equals(questionsCounter))
{
counter++;
eachCounter = 0;
}
}
I don't know the logic behind your program here, I see you're using counter as a loop variable and changing it in between, so it might not iterate through all elements of filteredList[0].subcategories[] serially. However, if you want to traverse through all elements of filteredList[0].subcategories[] serially using foreach, this is how its done.
Edit:
For traversing through subcategories[0], [1] and so on:
foreach (var item in filteredList[0].subcategories)
{
// item is filteredList[0].subcategories[0], filteredList[0].subcategories[1] and so on.
foreach(element in item)
{
//element is item[0], item[1] and so on i.e
// filteredList[0].subcategories[0].questionAnswer[0]
// filteredList[0].subcategories[0].questionAnswer[1]
// filteredList[0].subcategories[0].questionAnswer[2]
// .
// .
// filteredList[0].subcategories[1].questionAnswer[0]
// filteredList[0].subcategories[1].questionAnswer[1]
// .
// .
}
}
Use a for loop
int eachCounter = 0;
for(int i = 0; i < filteredList[0].subcategories[i].questionanswer.Count; i++)
{
int questionsCounter = filteredList[0].subcategories[i].questionanswer.Count;
eachCounter++; // I am not sure why you are doing this or what the purpose is
if (eachCounter.Equals(questionsCounter))
{
eachCounter = 0;
}
}

Check if "for loop" is in first or last iteration in C#

I have a for loop in my list which I want to do something different with the first and the last iterations. I found this question which is about foreach loop.
How Can I do achieve purpose in a for loop ?
string str;
for (int i = 0; i < myList.Count; i++)
{
//Do somthin with the first iteration
str = "/" + i;
//Do somthin with the last iteration
}
I want to know if there's an other way than this:
for (int i = 0; i < myList.Count; i++)
{
if (i == 0)
{
//Do somthin with the first iteration
}
str = "/" + i;
if (i == myList.Count-1)
{
//Do somthin with the last iteration
}
}
If you wanted to entirely avoid conditionals in your for loop (and that's what it seems like based on the details you've provided), you should just execute whatever logic you like on the first and the last items. Then, you can structure your for loop so that it ignores the first and last elements in the enumerable (initialize i as 1 and change your condition to i < myList.Count - 1).
if (myList != null && myList.Count >= 2)
{
YourFirstFunction(myList[0]);
for (int i = 1; i < myList.Count - 1; i++)
{
YourSecondFunction(myList[i])
}
YourThirdFunction(myList[myList.Count - 1]);
}
Replace YourNFunction with whatever logic you'd like to apply to the first index, the between indices, and the last index, respectively.
Note that I've checked whether myList has two or more items - I don't think this logic makes any sense unless, at the very least, the first and the last indices aren't the same. Given that you also plan to do something with items in-between, you might want to change it to 3, so as to ensure that you've always got a distinct beginning, middle, and end.
You can start the loop at 1 and do first iteration processing outside. Something like this:
if(myList != null && myList.Count > 0){
// Process first and last element here using myList[0] and myList[myList.Count -1]
}
for(int i = 1; i <myList.Count - 1;i++){
// process the rest
}
You will need to consider scenario where myList has only one element.
Just do something with the first and last items, and then loop through the rest:
if (myList != null && myList.Any())
{
// Do something with the first item here
var str = "** START **" + myList.First();
for (int i = 1; i < myList.Count - 1; i++)
{
str += "/" + i;
}
//Do something with the last item here
if (myList.Count > 1) str += myList.Last() + " ** END **";
}

mulit select listbox in wpf

how i can select five items in the single click on the list box??
if i click any item, i just want to +2 and -2 from the selected index. so my single click need to select five items in the listview.
Am using C#(WPF).
I am not sure what you want to do exactly, but trying. =)
Have a look at the Click event of the ListBox. You can do anything in there, including selecting five items of your choice. You can do it like this (untested, but gives you an idea):
int sindex = listBox1.SelectedIndex;
listBox1.SelectedItems.Clear();
for(int i = Math.Max(sindex - 2, 0); i < Math.Min(sindex + 2, listBox1.Items.Count()), i++)
{
listBox1.SelectedItems.Add(listBox1.Items[i]);
}
Another thing would be setting the SelectionMode to Multiple or Extended. Does this result in the behaviour you are looking for?
have a look at selectionchanged event, and get the index of the selected item and make it +2 and -2
i tried it like this and it works:
void list_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
int idx = list.SelectedIndex;
int startIdx = idx - 2;
int endIdx = idx + 2;
if (startIdx < 0)
{
startIdx = 0;
}
if (endIdx >= list.Items.Count)
{
endIdx = list.Items.Count-1;
}
for (int i = startIdx; i <= endIdx; i++)
{
if (i != idx)
{
list.SelectedItems.Add(list.Items[i]);
}
}
}
one problem with this code is you can still use ctrl to select another item so it makes the selecteditems count increased

Categories