I have a list<>, filled with objects of my class. That one is working fine. Now I want to load the last 10 elements to a new list<>, which is sorted upside-down. So the last Element will be the first of the new List<> and the 10th will be the last one in the new List<>.
Usually this shouldn't be such a hard task but I don't know... it iterates on the right way and should work in my opinion.
Both Lists<> are Lists<lastChanges>. lastChange is my class.
Here's what I got now:
// x represents the amount of elements for the new List<>
int x = 10;
// elems is the old list. if it contains less than 10 elements,
// x should be the amount instead of 10
if (elems.Count < 10)
{
x = elems.Count;
}
// The start-index is made by elems.Count -> 10 Items -> the 10th item
// would get the index '9'
// as long as i is greater than the amount of the large List<>
// minus the wanted amount for the new List<>
// the loop is going to repeat
for (int i = elems.Count-1; i > elems.Count - x; i--)
{
// lastChanges is my class which both Lists are filled with
lastChanges lastArt = elems[i];
if (lastArt != null)
{
items.Add(lastArt);
}
}
What am I missing? I really do not think I'm still a beginner (of course much to improve) but I can't find an error here...
For example:
The elems-List does contain 2 Elements, then x would be equal 2. The for-loop would start:
for(int i=1;i>0;i--)
so the loop would run twice.
In the first run there would be 'lastArt' set equal to the second object of 'elems' and than be added to 'items,
in the second run, the first item would be added to 'items'.
So, both items are added to 'items', everything is fine.
But why do I keep getting errors? Both Objects are definetely != null...
Thank you!
edit:
I always get a 'NullReferenceException' in this line:
items.Add(lastArt);
Both Objects are definetely != null, so in my opinion it has to be an error in my iteration.