C
C#2y ago
9.h

❔ 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
Angius
Angius2y ago
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 list
9.h
9.h2y ago
I see, the challenge provided resource which used IEnumerable, thus I thought I should too I will try using list, then
Angius
Angius2y ago
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 simpler
9.h
9.h2y ago
I will try doing that later, but first I want to get it to work using list
9.h
9.h2y ago
Is this progress?
Angius
Angius2y ago
You initialized the list to a given size, but it doesn't have any elements There's no ith element
9.h
9.h2y ago
I 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
Angius
Angius2y ago
Ah, wait, I see what the issue might be
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
var l = new List<int>(3);
for (var i = 0; i < l.Count; i++)
l[i] = 7;
l
var l = new List<int>(3);
for (var i = 0; i < l.Count; i++)
l[i] = 7;
l
Result: List<int>
[]
[]
Compile: 535.335ms | Execution: 53.964ms | React with ❌ to remove this embed.
Angius
Angius2y ago
This works... kinda
MODiX
MODiX2y ago
Angius#1586
REPL Result: Failure
var l = new List<int>(3);
for (var i = 0; i < 3; i++)
l[i] = 7;
l
var l = new List<int>(3);
for (var i = 0; i < 3; i++)
l[i] = 7;
l
Exception: ArgumentOutOfRangeException
- Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
- Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
Compile: 536.939ms | Execution: 50.378ms | React with ❌ to remove this embed.
Angius
Angius2y ago
While this throws Yeah, because the count of the list is still 0
9.h
9.h2y ago
where does l.Count come from in this case
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
new List<int>(300).Count
new List<int>(300).Count
Result: int
0
0
Compile: 447.376ms | Execution: 25.035ms | React with ❌ to remove this embed.
9.h
9.h2y ago
l doesn't exist prior to that line
Angius
Angius2y ago
List has a property Count
9.h
9.h2y ago
Oh by l did you mean List? So List.Count
Angius
Angius2y ago
Angius
Angius2y ago
Yes l is the list
9.h
9.h2y ago
oh shid ooga booga I'm smart Okay I shall try that
Angius
Angius2y ago
So, one of two ways I'd go about it Either use an array instead of a list
9.h
9.h2y ago
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?
Angius
Angius2y ago
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 anyway
9.h
9.h2y ago
Do 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
Angius
Angius2y ago
Which list would List.Count refer to?
9.h
9.h2y ago
Exactly I realized that when I looked at it again Thank you I'll try that
9.h
9.h2y ago
This does not work by the way? Unless I did something wrong which is likely
Angius
Angius2y ago
Odd, what's the error?
9.h
9.h2y ago
Oh yeah I should mention I am using the .net framework and stuff I don't know if that is relevant but
Angius
Angius2y ago
Ah, the old one?
9.h
9.h2y ago
Wait lol it fixed itself lmao
Angius
Angius2y ago
Might matter, dunno
9.h
9.h2y ago
I let it stay like that for a minute while waiting for an answer and it stopped displaying as an error
Angius
Angius2y ago
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?
9.h
9.h2y ago
This one to be exact
9.h
9.h2y ago
Does what you said still apply
Angius
Angius2y ago
Yeah .NET Framework is old and ass, but it works mostly well
9.h
9.h2y ago
Okay, so mainly my college using this one and basically everything I try works so why change it?
Angius
Angius2y ago
Well, depending on the version 4.8 is decent, 2.0 is hell And so on
9.h
9.h2y ago
How can I check my version?
Angius
Angius2y ago
In the csproj file Or right-click on your project in the solution explorer and open the properties
9.h
9.h2y ago
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
Angius
Angius2y ago
Not horrible Not that much changed since then, so what I say should apply
9.h
9.h2y ago
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
Angius
Angius2y ago
Yeah, it's fine if your college uses it
9.h
9.h2y ago
Angius
Angius2y ago
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
9.h
9.h2y ago
How can I display the array in a tangible form so I can confirm whether or not my code works as intended?
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
class Person{};
var p = new Person();
Console.Write(p);
class Person{};
var p = new Person();
Console.Write(p);
Console Output
Submission#0+Person
Submission#0+Person
Compile: 601.349ms | Execution: 73.677ms | React with ❌ to remove this embed.
Angius
Angius2y ago
Could use string.Join() for example To join all the elements with a comma or something
9.h
9.h2y ago
intellisense is a blessing But it did not work hm I put this before the console writeline string.Join(",", l.ToArray());
MODiX
MODiX2y ago
Angius#1586
REPL Result: Success
var list = new List<int>(){1, 2, 3, 4, 5, 6};
Console.Write(string.Join(", ", list));
var list = new List<int>(){1, 2, 3, 4, 5, 6};
Console.Write(string.Join(", ", list));
Console Output
1, 2, 3, 4, 5, 6
1, 2, 3, 4, 5, 6
Compile: 589.822ms | Execution: 81.709ms | React with ❌ to remove this embed.
Angius
Angius2y ago
It does work Your list might be empty
9.h
9.h2y ago
Likely to be the case I fixed it and it does not display anything so yeah
Angius
Angius2y ago
Aight, show your current code, let's see
9.h
9.h2y ago
Should I just take a ss or do the fancy code thing
Angius
Angius2y ago
Post the fancy code $codegif
9.h
9.h2y ago
Console.WriteLine("Enter the number:");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the length:");
int length = Convert.ToInt32(Console.ReadLine());
var l = new List<int>(length);
for(int i = 0; i < l.Count; i++)
{
l[i] = num1 * i;
}
Console.WriteLine(string.Join(", ", l));
Console.ReadLine();
Console.WriteLine("Enter the number:");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the length:");
int length = Convert.ToInt32(Console.ReadLine());
var l = new List<int>(length);
for(int i = 0; i < l.Count; i++)
{
l[i] = num1 * i;
}
Console.WriteLine(string.Join(", ", l));
Console.ReadLine();
oop
Angius
Angius2y ago
Well, the list will have a count of 0 It has a size of length, but there aren't any elements there
9.h
9.h2y ago
also another problem is that the first element will be 0 since i is 0
Angius
Angius2y ago
Sure is
9.h
9.h2y ago
any num * 0 = 0 Add() wouldn't work would it?
Angius
Angius2y ago
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 list
reflectronic
reflectronic2y ago
new List<int>(length); is going to do the exact same thing as new List<int>();. it's not what you want here
9.h
9.h2y ago
9.h
9.h2y ago
the first one works I'ma try using an array too to get familiar with it Thanks for all the help btw
Henkypenky
Henkypenky2y ago
in case no one mentioned, don't forget the potential problems with Convert.ToInt32 TryParse is a much safer choice
9.h
9.h2y ago
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
Henkypenky
Henkypenky2y ago
$tryparse
MODiX
MODiX2y ago
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.
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
return Convert.ToInt32(null); //returns 0. null should not be considered as 0 ever
return Convert.ToInt32("asdf"); //throws FormatException
(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.
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
var number = int.Parse("abc"); //throws FormatException
var number = int.Parse(""); //throws FormatException
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__
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
if (int.TryParse(someInput, out var result))
{
Console.WriteLine($"Thanks for giving me the following number: {result}!");
}
else
{
Console.WriteLine("You didn't give me a valid number :c");
}
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.
9.h
9.h2y ago
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
Henkypenky
Henkypenky2y ago
not only strings, but yes, basically with TryParse you don't need to manage exceptions and can check the result of said parse
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server