Remove n number of rows from a list - c#

How do I remove the last two rows from a List.
At present, I am removing the 2 rows manually as shown below. However, there might be an instance where I have to define the number of rows to be removed as n. So, it will remove n number of rows from the bottom of the list. How can I make this change?
rows.RemoveAt(rows.Count - 1);
rows.RemoveAt(rows.Count - 2);

You could use RemoveRange:
rows.RemoveRange(rows.Count - n, n);

You could use LINQ:
rows = rows.Take(rows.Count - n).ToList();

As Spender said, there is a potential issue in your code. I call this a "Index Race Condition". After you remove the last element, something else becomes the new last Element. It is something you have to look out for with Indexed Collections. Keyd collections do not suffer from it.
In addition to what others said regarding using "RemoveRange" (if availible) or LINQ, there is also a chance you got the wrong collection type.
The Queue[T] and the Stack[T] are specialized collections for first-in, first-out and first-in, last-out cases respectively.

Related

Insert into ObservableCollection per int comparison

Say I have an ObservableCollection with two items:
0: dateUnix: 333
1: dateUnix: 222
Now I want to add a new Item:
dateUnix: 300
If I just were to use the .add() method, the item would get added at the end. But I want the item to be inserted between 222 and 300 since this would make the list sorted.
How do I insert an item at a certain position where it is less then item value after and higher then item value before?
Of the top, I can think of two ways of doing this.
One would be, as was pointed out in the comments, to just insert and sort afterwards.
Another, more complex and more rewarding way would be to find the index of the first item greater or lesser than the one you're inserting and insert it at that index. Your list seems to be sorted in descending order, so it'd need to be the first lesser than.
You could achieve this using LINQ:
ObservableCollection<Int> collection = new ObservableCollection(new List<int>{333,222}); // == [333,222]
Int toInsert = 300;
collection.Insert(collection.IndexOf(collection.First(elem => elem < toInsert)), toInsert); // output == [333,300,222]
See this Fiddle for a working example.
If your collection is already sorted, just find the appropriate index to insert the element at (either via a linear or the faster binary search) and use Insert to store the element at that specific index.

What is the inverse of ImageList.RemoveAt(index1);?

I tried many times to resolve this case but I always get an error because it's an Image in an ImageList. What code do I need to literally re-add the removed Image from the list. This is my code (The final line doesn't work).
int index9 = random.Next(0, normalCards1.Count - 1);
pictureBox9.Image = normalCards1[index9];
normalCards1.RemoveAt(index9);
...
normalCards1.Insert(index9);
you need to pass T item as well with index.
you can add it back this way:
normalCards1.Insert(index9,pictureBox9.Image);
See List.Insert Method MSDN docs here
ImageListCollection which is the type of ImageList.Images does not provide a way to insert items by index.
If you want to shuffle or somehow else reorder images you need to remove them all and add them again after reordering. I.e. adding all images to a List<T>, sort, and use AddRange.
You can also try using indexed access (imageList.Images[3] = ... ) to swap items.

get fixed number of items from array list c#

I would like to create a list variable of items from another list. So lets say I have a list of 100 items I would like to pull items 25 - 35 and put them inside of another list. is there a way of doing this without calling a big for statement and pulling out the element one by one and putting that into a list.
you can use .Skip and .Take from System.Linq ....
Like this:
var result = myList.Skip(24).Take(10);
and if you need use ToList on the result to get another list
For a List<T>, you can use the GetRange Method.
Creates a shallow copy of a range of elements in the source List(Of
T).
Do note that the second argument represents the count of elements in the range, not the end-index of the range.
Since you mention ArrayList, I should point out that while it too has a GetRange, method, the type is considered essentially legacy since .NET 2.0.
Use both Take and Skip
var newList = oldList.Skip(25).Take(10);

Shortest way to bind a certain amout of items from a list to a data source?

Anyone know how to select a certain amount of items in a List to bind to a DataSource? Basically I'm getting back 10 items (which I don't have control over) and I only need to show 5. Originally I was thinking of using a loop and adding 5 items to a new list but that seems like a lot of code. Is there an expression that I can use to select the first 5?
//Returns a List<DataItem>
MyDataListControl.DataSource = Helper.GetDataItems(); //<= Possible expression?
You may take a look at the Skip and Take LINQ extension methods. So in your case if you wanted to take only the first 5 elements of some IEnumerable<T>:
MyDataListControl.DataSource = Helper.GetDataItems().Take(5).ToList();
What about List's GetRange method? Have you tried that? I don't the internal workings of the method; whether it also creates a new list or not.
GetRange(int index, int count)
Here is the msdn link for it.
RemoveRange will probably be best as you won't have to instanciate a new list, unless that happens internally anyway.. Just make sure you're always getting 10 items or you'll potentially get an ArgumentOutOfRangeException.
list.RemoveRange(5, 5);
That should leave you with the first five items.

Frequent inserts into sorted collection

I have sorted collection (List) and I need to keep it sorted at all times.
I am currently using List.BinarySearch on my collection and then insert element in right place. I have also tried sorting list after every insertion but the performance in unacceptable.
Is there a solution that will give better performance? Maybe I should use other collection.
(I am aware of SortedList but it is restricted to unique keys)
PowerCollections has an OrderedBag type which may be good for what you need. From the docs
Inserting, deleting, and looking up an
an element all are done in log(N) + M
time, where N is the number of keys in
the tree, and M is the current number
of copies of the element being
handled.
However, for the .NET 3.5 built in types, using List.BinarySearch and inserting each item into the correct place is a good start - but that uses an Array internally so your performance will drop due to all the copying you're doing when you insert.
If you can group your inserts into batches that will improve things, but unless you can get down to only a single sort operation after all your inserting you're probably better off using OrderedBag from PowerCollections if you can.
If you're using .Net 4, you can use a SortedSet<T>
http://msdn.microsoft.com/en-us/library/dd412070.aspx
For .Net 3.5 and lower, see if a SortedList<TKey,TValue> works for you.
http://msdn.microsoft.com/en-us/library/ms132319.aspx
Try to aggregate insertions into batches, and sort only at the end of each batch.

Categories

Resources