38 Replies
i wanna get input from user which contains line of numbers, than convert those numbers into list<int>, sort it, so that i could find min and max value
what is wrong with this?
You don't need to give the list an initial size
And use
.Add()
to add elements to itbut why doesnt my method work?
Retax#0813
REPL Result: Failure
Exception: ArgumentOutOfRangeException
Compile: 410.056ms | Execution: 23.683ms | React with ❌ to remove this embed.
Because you set the size of the list
But it doesn't actually have anything inside
So you can't set those things
wai what
You say "there will be 70 boxes in the truck"
But there are no boxes
the constructor sets the capacity, not the count
So you can't put a thing in the 7th box
that kinda sucks
No, why?
The initial capacity you set does not mean there are actually values (like say,
0
) in there yet, the internal array is set to that size, but it doesn't let you access it directly unless you actually added iti thought c# would fill it with 0s or nulls
would be convinient
Makes things easier for you, though. No need for messing with the index and stuff
i thought it would be slightly slower than assigning with index
Not in any way that would matter
wait but why would you set size in the first place
Sure, if you are adding 1 million items/second it might be 10ms slower
var list = Enumerable.Repeat(default(Type), 99).ToList();
I'd probably use something like thisWhen the list reaches capacity and you add one more element, the list gets doubled in size
That costs some performance
only as an optimization
Telling the list what size to expect causes it to not have to double the capacity
It's a minor optimization
ohhh
so, even if i create list of 70 numbers, list.add, than it will add into [0] index, not in [70]th index?
yes
Yeah
pretty cool than
thanks!
and you can't change the count of a list without adding elements until that count reaches the value you need
as far as I know
that makes sense
So you can rewrite
into just
this allocates more memory
probably
but yeah
that method is as bad as adding 99 zeros in a loop
but there's no other way you can do this with the default list implementation
btw, is there something better than this?
LINQ
instead of writing all of this
nah, i mean right from the string to list<int> nums
without spliting it into array -> converting to list
Ah
You can only really take text as input
So you will need to split it, and you will need to parse it
jesus that sucks so badly
Eh, you can always write some simple helper methods
Or some such