❔ Indexing with [] to an expression type IEnumerable / array
Hi, I am trying to do some c# challanges as a way to begin my c# journey, but I am currently stuck on this.
To elaborate, I am trying to fill each of the spaces in the array with (num1 * i), but I cannot. So far, I have been stuck for almost an hour while trying to do different things. I think, the main problem is that I have not created a space for the values to reside in the array, though I thought putting (length) in would solve that (spoiler, it did not)
74 Replies
IEnumerable
allows you only to enumerate the collection
It does not allow for random access, so indexing into it
You're creating a list, so... store it as a listI see, the challenge provided resource which used IEnumerable, thus I thought I should too
I will try using list, then
You can, but you'd have to
foreach
over the collection instead, or while
over it
Using a list where you create a list is much simplerI will try doing that later, but first I want to get it to work using list
Is this progress?
You initialized the list to a given size, but it doesn't have any elements
There's no
i
th elementI assumed that by adding size length to it, it would create the length amount of spaces I could put items into
How can I create the i th element? There has to be enough elements in the list to fit all i's up to length
Ah, wait, I see what the issue might be
Angius#1586
REPL Result: Success
Result: List<int>
Compile: 535.335ms | Execution: 53.964ms | React with ❌ to remove this embed.
This works... kinda
Angius#1586
REPL Result: Failure
Exception: ArgumentOutOfRangeException
Compile: 536.939ms | Execution: 50.378ms | React with ❌ to remove this embed.
While this throws
Yeah, because the count of the list is still 0
where does l.Count come from in this case
Angius#1586
REPL Result: Success
Result: int
Compile: 447.376ms | Execution: 25.035ms | React with ❌ to remove this embed.
l doesn't exist prior to that line
List
has a property Count
Oh by l did you mean List?
So List.Count
Yes
l
is the listoh shid
ooga booga I'm smart
Okay I shall try that
So, one of two ways I'd go about it
Either use an array instead of a list
Btw when you use var, do you use it for simplicity sake as var can be anything or should I use var instead of int too?
Or use the fact that a list is resizeable
I use it everywhere tbh
No reason not to
And
var x = 8;
and int x = 8;
are the exact same thing anywayDo you have to make the list a variable?
in this case var l
Can you just do List.Count instead
nonoonno
Wait
I am stupid
I understand
Which list would
List.Count
refer to?Exactly
I realized that when I looked at it again
Thank you I'll try that
This does not work by the way? Unless I did something wrong which is likely
Odd, what's the error?
Oh yeah I should mention I am using the .net framework and stuff
I don't know if that is relevant but
Ah, the old one?
Wait lol it fixed itself lmao
Might matter, dunno
I let it stay like that for a minute while waiting for an answer and it stopped displaying as an error
VS gonna VS I guess ¯\_(ツ)_/¯
Any particular reason you're using some old version of the framework to learn?
And what version is it, exactly?
This one to be exact
Does what you said still apply
Yeah
.NET Framework is old and ass, but it works mostly well
Okay, so mainly my college using this one and basically everything I try works so why change it?
Well, depending on the version
4.8 is decent, 2.0 is hell
And so on
How can I check my version?
In the csproj file
Or right-click on your project in the solution explorer and open the properties
I cannot find the version in the csproj file I'll try the other thing
Oh no no nvm I found it
4.7.2
Not horrible
Not that much changed since then, so what I say should apply
I am still a beginner plus this is what my college is using so I'd rather use it unless it will severely hinder my development
Yeah, it's fine if your college uses it
As long as you're aware it's outdated and we got many a cool feature since then
Yep, that's how complex objects get printed
You get their name
How can I display the array in a tangible form so I can confirm whether or not my code works as intended?
Angius#1586
REPL Result: Success
Console Output
Compile: 601.349ms | Execution: 73.677ms | React with ❌ to remove this embed.
Could use
string.Join()
for example
To join all the elements with a comma or somethingintellisense is a blessing
But it did not work hm
I put this before the console writeline
string.Join(",", l.ToArray());
Angius#1586
REPL Result: Success
Console Output
Compile: 589.822ms | Execution: 81.709ms | React with ❌ to remove this embed.
It does work
Your list might be empty
Likely to be the case
I fixed it and it does not display anything so yeah
Aight, show your current code, let's see
Should I just take a ss or do the fancy code thing
Post the fancy code
$codegif
oop
Well, the list will have a count of
0
It has a size of length
, but there aren't any elements therealso another problem is that the first element will be 0
since i is 0
Sure is
any num * 0 = 0
Add() wouldn't work would it?
The issue is that
Count
is 0
, so no, it would not
You can solve it two ways:
1. Use the length
you got, not the list's .Count
for your loop, then use .Add()
2. Use an array instead of a listnew List<int>(length);
is going to do the exact same thing as new List<int>();
. it's not what you want herethe first one works
I'ma try using an array too to get familiar with it
Thanks for all the help btw
in case no one mentioned, don't forget the potential problems with Convert.ToInt32
TryParse is a much safer choice
Such as?
If I want to include numbers in an array/list, what else should I do other than Convert.ToInt32? In my college the teacher taught me to do that whenever trying to get an int from the user
$tryparse
The TryParse pattern is considered best practice of parsing data from a string:
- a TryParse method returns
true
or false
to inform you if it succeeded or not, so you can use it directly in a condition,
- since C# 7 you can declare a variable that will be used as an out
argument inline in an argument list,
- it forces you to check if the out
argument contains valid data afterwards,
Avoid: Convert.ToInt32 — it's a bad choice for parsing an int
. It exists only for backwards compatibility reasons and should be considered last resort. (Note: Convert does contain useful conversion methods: To/FromBase64String
, To/FromHexString
, ToString(X value, int toBase)
, ToX(string? value, int fromBase)
)
Avoid: int.Parse — you have to use a try
/catch
statement to handle invalid input, which is a less clean solution.
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__ Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
I am a bit confused as to what parsing is, and google's answer is not the most helpful
Basically is parsing changing a string into a value
not only strings, but yes, basically
with TryParse you don't need to manage exceptions and can check the result of said parse
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.