C
C#8mo ago
sebt

❔ In need of a way to process inputs to produce outputs, other than using hardcoded if statements

Hi all, I currently have a program that prompts the user to ask a question, then based on the parameters in the user's input, my code will output the answer to said question. However, as of right now I have it so my code is just using a lot of if statements and structured in a way which is
if (input.contains(arrayX[1]) && input.contains(arrayY[1])){
Console.WriteLine("inset question answer here");}
if (input.contains(arrayX[1]) && input.contains(arrayY[1])){
Console.WriteLine("inset question answer here");}
and I essentially have it all hardcoded for each input however this takes up so many lines of code so I was wondering if anybody could help me find a more efficient way of carrying out this process.
297 Replies
Angius
Angius8mo ago
Could maybe store it as a list of classes?
record Question(string ParamOne, string ParamTwo, string Question);
record Question(string ParamOne, string ParamTwo, string Question);
var questions = new List<Question>();
var question = questions.First(q => input.Contains(q.ParamOne) && input.Contains(q.ParamTwo));
Console.WriteLine(question.Question);
var questions = new List<Question>();
var question = questions.First(q => input.Contains(q.ParamOne) && input.Contains(q.ParamTwo));
Console.WriteLine(question.Question);
Could even store the questions as JSON
sebt
sebt8mo ago
hmm i think i understand
Stan
Stan8mo ago
Yeah something like that. id have the parameters be an array, in the record, as well as the answer, possibly provided through a method that lets you extract data from the user question and just loop our Question instances to see what matches
sebt
sebt8mo ago
surely this will also be alot of hardcoded lines tho also?
Angius
Angius8mo ago
No Just those 3
Stan
Stan8mo ago
how come
Angius
Angius8mo ago
Store data in a json file
MODiX
MODiX8mo ago
Angius
Store data in a json file
React with ❌ to remove this embed.
sebt
sebt8mo ago
but in the code above, doesnt that only write the answer for when the input contains parameters 1 and 2 for the question, what about for when it contains parameters 3 and 4 for example
Stan
Stan8mo ago
thats why you use an array instead owo
sebt
sebt8mo ago
ok so lets say i use a 2d array or a 1d array surely i still have to hardcode for every parameter sry btw i am new so i might not be 100% understanding it correctly
Angius
Angius8mo ago
// data.json
[
{
"Params": ["cat", "dog"],
"Question": "Unga bunga?"
},
{
"Params": ["whoop", "dee", "doo"],
"Question": "Peepee poopoo?"
}
]
// data.json
[
{
"Params": ["cat", "dog"],
"Question": "Unga bunga?"
},
{
"Params": ["whoop", "dee", "doo"],
"Question": "Peepee poopoo?"
}
]
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
There
sebt
sebt8mo ago
so the top code isnt in visual studio it is in a json file
Angius
Angius8mo ago
It is a part of the project, yes
sebt
sebt8mo ago
sorry i have never used a json file before to hold text how do i use the data.json to make it work with the program
Angius
Angius8mo ago
Like I wrote Place the file next to your .csproj Mark it to copy always or copy if newer Done
sebt
sebt8mo ago
what do i paste it into a new text file then put that next to the csproj in the folder
Angius
Angius8mo ago
The code I posted is literally a working sample Well, almost, you'll need to get the actual input There, now it's a working sample
sebt
sebt8mo ago
but when i psate it into vs it comes up with a load of errors
Angius
Angius8mo ago
Like?
sebt
sebt8mo ago
No description
sebt
sebt8mo ago
bunch of syntax eorrs
Angius
Angius8mo ago
The JSON data is it's own JSON file
sebt
sebt8mo ago
yeah how do i do that
Angius
Angius8mo ago
Make a file?
sebt
sebt8mo ago
yh do i put it in the same folder as my consoleapp is in
Angius
Angius8mo ago
Yes As I said already, next to the .csproj
sebt
sebt8mo ago
ok done but now its sayins jsonserializer dosent exist and Question coudlnt be foud
Angius
Angius8mo ago
Use quick fixes to import the necessary namespace And, right, you will need to create the Question class Or a record
sebt
sebt8mo ago
ok i used quick fixes now its saying object doesnt contain a definition for First and theres no quick fixes that solveit
Angius
Angius8mo ago
Quick fixes again You need System.Linq namespace
sebt
sebt8mo ago
i dont understand wdym
Angius
Angius8mo ago
Use the quick fixes on First
sebt
sebt8mo ago
it only says convert to top level statemetns
Angius
Angius8mo ago
Just like using it on JsonSerializer included System.Text.Json namespace, using it on First will include System.Linq Then include the namespace manually
sebt
sebt8mo ago
so shall i make a new class for First
Angius
Angius8mo ago
No, why? Include the namespace
sebt
sebt8mo ago
what do you mean inclued the namespac
Angius
Angius8mo ago
using System.Linq;
sebt
sebt8mo ago
yeah ive typed that but visual studio greys it out and says its unnecessary
Angius
Angius8mo ago
Show your code
Stan
Stan8mo ago
and your error
sebt
sebt8mo ago
do u want it in a screenshot or typed out
Angius
Angius8mo ago
$code
MODiX
MODiX8mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Angius
Angius8mo ago
And maybe a screenshot of the errors
sebt
sebt8mo ago
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
}
}

public record Question();
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
}
}

public record Question();
Angius
Angius8mo ago
Well
sebt
sebt8mo ago
No description
Angius
Angius8mo ago
Your Question has no properties
sebt
sebt8mo ago
yeah i know
Angius
Angius8mo ago
And you're trying to access its Params and Question properties Can't access what doesn't exist
sebt
sebt8mo ago
but i thought they were stored in the json file
Stan
Stan8mo ago
hwck is Params anyway, i thought it was some json thing i didnt know about for a moment
Angius
Angius8mo ago
The json file just stores the data
sebt
sebt8mo ago
ok
Stan
Stan8mo ago
yeah, we're in C# baby, everything needs types here
sebt
sebt8mo ago
so what do i do and also how do i fix the First error
Angius
Angius8mo ago
* The record has no properties * That's an issue * How do I fix that issue? Take a guess
Stan
Stan8mo ago
Gotta add the Params and Question properties to your record so c# knows how to interpret your json file
Angius
Angius8mo ago
Deserializing from Json will put data from a property of name X in the Json file, into a property of name X in whatever class you give it
sebt
sebt8mo ago
oh so it like converts it
Stan
Stan8mo ago
json is rly just a way to store data in a (very commonly used mind you) format. Deserializing is essentially grabbing the data and putting it into your class
sebt
sebt8mo ago
so whats the point of storing it in a json file if it needs to be redefined in c#
Angius
Angius8mo ago
Because it's easier?
Stan
Stan8mo ago
you only define the properties in c# rather than all the actual questions and answers
sebt
sebt8mo ago
ohh
Stan
Stan8mo ago
if you have a lot of data, this will save a lot of hardcoded crap
sebt
sebt8mo ago
yeah
Stan
Stan8mo ago
plus json is used all over, its very useful to learn it, even if this particular application doesnt rly "need" it
Angius
Angius8mo ago
Would you rather define one class and data in the Json file, or still define that class and the data as
var data = new List<Question>() {
new Question {
Params = new string[] { "cat", "dog" },
Question = "Unga bunga?"
}
};
var data = new List<Question>() {
new Question {
Params = new string[] { "cat", "dog" },
Question = "Unga bunga?"
}
};
sebt
sebt8mo ago
so how do i define the properties of the data in my json file inside my question record
Angius
Angius8mo ago
You wanted to avoid hardcoding the data in your source code That's how
MODiX
MODiX8mo ago
Angius
Could maybe store it as a list of classes?
record Question(string ParamOne, string ParamTwo, string Question);
record Question(string ParamOne, string ParamTwo, string Question);
var questions = new List<Question>();
var question = questions.First(q => input.Contains(q.ParamOne) && input.Contains(q.ParamTwo));
Console.WriteLine(question.Question);
var questions = new List<Question>();
var question = questions.First(q => input.Contains(q.ParamOne) && input.Contains(q.ParamTwo));
Console.WriteLine(question.Question);
React with ❌ to remove this embed.
Angius
Angius8mo ago
Refer to this
sebt
sebt8mo ago
what so like this
public record QuestionChooser(string ParamOne, string ParamTwo, string Question);
public record QuestionChooser(string ParamOne, string ParamTwo, string Question);
Stan
Stan8mo ago
that might work with modern c#? im not sure
Angius
Angius8mo ago
Of course it will You will need to adjust the parameters though Look at the Json There's Params that's an array of strings And there's Question that's a single string Those will have to be the properties of your record
sebt
sebt8mo ago
so
public record QuestionChooser(string[] Params, string Question);
public record QuestionChooser(string[] Params, string Question);
?
Angius
Angius8mo ago
Yep
Stan
Stan8mo ago
yeah thatll do :3
sebt
sebt8mo ago
so how do i fix this error with data.First
Stan
Stan8mo ago
you still get it?
sebt
sebt8mo ago
yh
Stan
Stan8mo ago
might need to make it a List<string> instead of array
Angius
Angius8mo ago
Nah .First() works on IEnumerable
sebt
sebt8mo ago
CS1061 'object' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'object' could be found
Angius
Angius8mo ago
An array does implement IEnumerable So For some reason data is of type object Huh What if you replace that var with List<Question>? The var data with List<Question> data
Stan
Stan8mo ago
man this third person debugging shit is weird, feels like a skill on its own
sebt
sebt8mo ago
i had to change the name of the record to QuestionChooser because the string parameter was called Question btw
Angius
Angius8mo ago
Ah
Stan
Stan8mo ago
5head
Angius
Angius8mo ago
Maybe that was the issue, yeah Good thinking
sebt
sebt8mo ago
but im getting more errors now i changed var to list haha it says data is already defined
Angius
Angius8mo ago
Do you have another variable named data somewhere?
sebt
sebt8mo ago
yeah
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);
but it was like that before and the error didnt show
Angius
Angius8mo ago
So you... declared a new variable called data Instead of changing the var here to List<Question like I said Or, well, List<QuestionChooser> now
sebt
sebt8mo ago
no thats in teh code above
Angius
Angius8mo ago
Show your code
sebt
sebt8mo ago
my code now as it stands is
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);

var input = Console.ReadLine();

List<QuestionChooser> data = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(Question.QuestionChooser);
}
}

public record QuestionChooser(string[] Params, string Question);
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);

var input = Console.ReadLine();

List<QuestionChooser> data = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(Question.QuestionChooser);
}
}

public record QuestionChooser(string[] Params, string Question);
Stan
Stan8mo ago
yeah you have two variables called data cant do that
MODiX
MODiX8mo ago
sebt#6912
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
}
}

public record Question();
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<Question>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.Question);
}
}

public record Question();
React with ❌ to remove this embed.
Angius
Angius8mo ago
It was named question Why'd you rename it?
sebt
sebt8mo ago
wtf my bad i didnt mean to idk how that happened
Stan
Stan8mo ago
no stress lol
sebt
sebt8mo ago
im still getting this error now though even after renaming it back to question and having it as List<QuestionChooser> question = ...
Angius
Angius8mo ago
Because it's a QuestionChooser now Not a list anymore You can just use var tbh
sebt
sebt8mo ago
ok i put it back to var
Stan
Stan8mo ago
yeah var auto figures out what the type is. the problem before is that you tried to give two different variables the same name. compiler gets brainzapped by that
sebt
sebt8mo ago
yeah i gotchu but the compiler is still giving me the same error as before
Stan
Stan8mo ago
what error was that?
sebt
sebt8mo ago
CS1061 'object' does not contain a definition for 'First' and no accessible extension method 'First' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
Angius
Angius8mo ago
Show code again
sebt
sebt8mo ago
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.QuestionChooser);
}
}

public record QuestionChooser(string[] Params, string Question);
using System.Linq;

internal class Program
{
private static async Task Main(string[] args)
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);

var input = Console.ReadLine();

var question = data.First(q => q.Params.All(p => input.Contains(p)));

Console.WriteLine(question.QuestionChooser);
}
}

public record QuestionChooser(string[] Params, string Question);
Stan
Stan8mo ago
dafuq lol
Angius
Angius8mo ago
This should, by all accounts, work
Stan
Stan8mo ago
data is List<QuestionChooser> which certainly has a First() can you try data.First() without the magic, see if that does the same thing. id also put a breakpoint to check what it thinks the value of question is at that point just for debugging purposes
sebt
sebt8mo ago
yeah data.first(); still the same error
Stan
Stan8mo ago
if you hover over "data" what does it say the type is
sebt
sebt8mo ago
object?
Stan
Stan8mo ago
lolwhy
Angius
Angius8mo ago
what It has no right to be object?
Stan
Stan8mo ago
man i dont have my code setup so i cant even see wtf is going on rn fucking yolo cast it as a list? XD idk fam
sebt
sebt8mo ago
No description
sebt
sebt8mo ago
i dont know what to do lol
Stan
Stan8mo ago
ok fuck this im booting into windows lol this is insane
sebt
sebt8mo ago
haha
Angius
Angius8mo ago
Wait Crazy theory Did the quick fixes on JsonSerializer perhaps create a new class named JsonSerializer?
Stan
Stan8mo ago
ohhhh
Angius
Angius8mo ago
Do you have any other files in the project, any other classes?
sebt
sebt8mo ago
yeah it did
Stan
Stan8mo ago
thats gotta be it hahaha
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
i didnt see the using statement i think
Angius
Angius8mo ago
Ah Yeah delete that
sebt
sebt8mo ago
the entire class> ?
Angius
Angius8mo ago
The whole file
Stan
Stan8mo ago
the entire JsonSerializrr file not ur actual code
sebt
sebt8mo ago
ok done it
Angius
Angius8mo ago
Now, JsonSerializer will be highlighted in red Use quick fixes
sebt
sebt8mo ago
No description
Angius
Angius8mo ago
And pick the fix that says to include the required namespace Or include the namespace manually using System.Text.Json;
sebt
sebt8mo ago
ok done it fixed it now im getting another error but for questionchooser
sebt
sebt8mo ago
No description
Angius
Angius8mo ago
Becase the property is Question Not QuestionChooser
Stan
Stan8mo ago
usually u ctrl+. and see if u can import the thing, cuz what it did now is assume JsonSerializer is a class you made rather than a .NET class
sebt
sebt8mo ago
ohh
Angius
Angius8mo ago
No description
Angius
Angius8mo ago
Works on my machine
sebt
sebt8mo ago
now i can run it but when it runs it says it coudlnt find the fil yet i have the file in ConsoleApp18 folder next to the csproj
Stan
Stan8mo ago
yay thats gooder
Angius
Angius8mo ago
Is the file copied? Right-click it, open its properties Select copy if newer or copy always
Stan
Stan8mo ago
the path it tries to read is relative to where ur exe is, so /bin/Debug/muh.json copy if newer essentially puts the file alongside ur exe whenever u compile
sebt
sebt8mo ago
where do i find copy if newer im on windows 11
Stan
Stan8mo ago
vscode or vs2022
sebt
sebt8mo ago
what can i not do it from properties
Stan
Stan8mo ago
what code editor do you use? visual studio 2022 or visual studio code
sebt
sebt8mo ago
visual studio 2022
Stan
Stan8mo ago
ok, u dragged the file into your project in visual studio? u should right click the file in the file list in visual studio and click properties
Angius
Angius8mo ago
The json file should be there in the solution explorer
Stan
Stan8mo ago
there youll be able to set it. i dont remember what the specific property is called tho..
sebt
sebt8mo ago
its in the solution explorer
Stan
Stan8mo ago
but its one of em, it opens a list that lets u pick what happens with the file
sebt
sebt8mo ago
No description
sebt
sebt8mo ago
i think if this is the solution explorer
Stan
Stan8mo ago
nah its gotta be on the left or right where u open your files bro this is hard xD
sebt
sebt8mo ago
here ???
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
nah it should basically be a file in your project leme fimd a screenshot
sebt
sebt8mo ago
k ty
Stan
Stan8mo ago
this thing it should be in that list alongside program.cs
sebt
sebt8mo ago
where what thing i dont think the image came thru
Stan
Stan8mo ago
oh
sebt
sebt8mo ago
ah ok
Stan
Stan8mo ago
No description
sebt
sebt8mo ago
so shall i set to copy if newer
Stan
Stan8mo ago
yes :3 and then i think ur there 😄 dont worry, it gets way less annoying once you get used to it its stuff we all ran into getting started
sebt
sebt8mo ago
ok i set to copy if newer and im still getting the same error lol wtf
Stan
Stan8mo ago
if u go to the project folder in windows explorer, in the bin/debug folder do u see the json file there? screenshot ur solution explorer if not pls
sebt
sebt8mo ago
wheres the bin/debug fodler
Stan
Stan8mo ago
rightclick ur project and "open containing folder" or something similar in there should be the bin folder, in that the debug folder
sebt
sebt8mo ago
yh its in there
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
and your code also says data.json right?
sebt
sebt8mo ago
yeah
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
and what was the error exactly?
sebt
sebt8mo ago
or is the txt
Stan
Stan8mo ago
ihh
sebt
sebt8mo ago
not making it work
Stan
Stan8mo ago
yeah txt bad
sebt
sebt8mo ago
what i did was make a new text file then copy and paste the info into there then save it as data.json
Stan
Stan8mo ago
first of all, in windows explorer u wanna enable show extensions
sebt
sebt8mo ago
how do i do that
Stan
Stan8mo ago
How do I show file extensions in Windows 11?
Show file extensions for known file types in Windows 11 by following these steps.
sebt
sebt8mo ago
yeah ok i gotchu
Stan
Stan8mo ago
then rename the file in ur project root (not bin/debug) then remove the wonky file from ur project
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
rightclick project, add file existing file and select the proper renamed file
sebt
sebt8mo ago
wait so i renamed the file now its a json actually
Stan
Stan8mo ago
yep heh
sebt
sebt8mo ago
then where do i remove the file
Stan
Stan8mo ago
actually, if visual studio doesnt complaina bout ot, ur good. just set it to copy if newer again sorry lol.. im used to older version of visual studio
sebt
sebt8mo ago
wait my solution explorer just disappeared how do i access it again
Stan
Stan8mo ago
is it tabbed or did u click x
sebt
sebt8mo ago
nvm i got it
Stan
Stan8mo ago
alright
sebt
sebt8mo ago
im getting fucked by visual studio right now ok so i changed it and made the new json file to copy if newer
Stan
Stan8mo ago
yeah, been there lol
sebt
sebt8mo ago
now im getting anotha error
Stan
Stan8mo ago
whats the error
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
alright thats good, thats just json syntax being fucked print ur json again please
sebt
sebt8mo ago
wym
Stan
Stan8mo ago
theres an error in your json file basically so it cant parse it
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
line 1 shouldnt say data.json thats why it cant read it
sebt
sebt8mo ago
oh ahh yeah ik the problem it was commented thats why its there but i removed the // not knwoing what i was doing
Stan
Stan8mo ago
heheh yeah its pretty strict usually you dont rly handwrite json either but it does unfortunately seem to be the best way to deal with data like this its more often used to communicate data between a webserver and a browser, or programatically written for data processing
sebt
sebt8mo ago
ok so the code runs now
Stan
Stan8mo ago
ayy nice
sebt
sebt8mo ago
but i dont know if it actualyl works because it prints nothing at the start until i input something and then it says
sebt
sebt8mo ago
No description
sebt
sebt8mo ago
so i think this is to do with the code now rather than the file reading but i dont know what im supposed to input @ZZZZZZZZZZZZZZZZZZZZZZZZZ did you have to input something in order for the code to print the contents of the json?
Stan
Stan8mo ago
its because First() must have something otherwise it crashes try FirstOrDefault() then it will return null instead of crash
sebt
sebt8mo ago
firstordefault gives me this error when i input something
Stan
Stan8mo ago
but you would have to do if (question == null) Console.WriteLine("no match") or something along those lines
sebt
sebt8mo ago
No description
Stan
Stan8mo ago
yeah, cuz without the null check, it will still crash basically it says it didnt find a match, which is probably a code problem, but we still need to have the program not explode when an undefined question is asked do you actually know what .All() and stuff does? i feel like its not the best approach for a beginner anyway if ur trying to learn
sebt
sebt8mo ago
i have no clue hahaa
Stan
Stan8mo ago
hehe fair
sebt
sebt8mo ago
but im this far i really want to make it work
Stan
Stan8mo ago
yeah of course
sebt
sebt8mo ago
using these ideas you know
Stan
Stan8mo ago
but we can make it more comprehensible if u want linq is amazing, but if you get thrown right into it as a beginner its super confusing
sebt
sebt8mo ago
fair enough
Stan
Stan8mo ago
id recommend you write your own implementation. knowing that data is a list (or array) of QuestionChooser. QuestionChooser has properties you can access using x.Param and x.Question i think you're better off using for loops and writing it yourself, but ill help u if you need help ofc
sebt
sebt8mo ago
i would love some help when i tried to do this myself i just end up hardcoding every possible outcome because i cant think of another way to do it
Stan
Stan8mo ago
alright, do you know how arrays and loops work?
sebt
sebt8mo ago
yeah
Stan
Stan8mo ago
oh and do you know what properties on a class or record do? like have you used it before? just to know how much i need to explain
sebt
sebt8mo ago
i have used classes and records before yeah in the code bascially
Stan
Stan8mo ago
perfect alright, so data is a List<QuestionChooser> which is basically just a fancy QuestionChooser[]. so what we can do is foreach (var qs in data) for starters and evaluate each to see if our input is useful
sebt
sebt8mo ago
ok there are 2 parameters for each question btw essentially 8x4 questions that can be asked
Stan
Stan8mo ago
right, but lets try to stay focused on the scope we're in or even simple processes get confusing
sebt
sebt8mo ago
ok my bad
Stan
Stan8mo ago
well its fine, just trying to communicate my way of thinking
sebt
sebt8mo ago
yh i gotchu all good
Stan
Stan8mo ago
right now we have qs which is an instance of QuestionChooser theres a few ways we can do it, but lets go with this one: we another foreach inside of there to iteratr the Params on qs so foreach (var p in qs.Params) and then we can check if input.Contains(p) normally i would put it in a function that we just return a bool out of at this point
sebt
sebt8mo ago
ok niec and the code will automatically read every instance in params from the json file?
Stan
Stan8mo ago
yep because we're looping over everything
sebt
sebt8mo ago
how do i say not instance but like each element of the array yeah ok nice so that saves me from having to do if inputcontains x or if inputcontainsy because this loop will see what the input contains exactly
Stan
Stan8mo ago
once you get the results, it depends what you wanna do with it really
sebt
sebt8mo ago
yeah
Stan
Stan8mo ago
do note, you wanna break out of the loop in a situation with a lot of data after you found your match thats why i would recommend creating a seperate method for it that returns whatever datatype you want as soon as the match is found returning out of a method breaks the loop. otherwise you gotta break out of two loops manually which is slightly annoying
sebt
sebt8mo ago
yeah that makes sense
Stan
Stan8mo ago
my description isnt fully accurate either, but i think youll figure out where the bug is, and if not, feel free to ask
sebt
sebt8mo ago
ok im gonna make something to eat then i will come and write the code with ur help thanks i probably will encoutner some problems tho so just letting u know lool
Stan
Stan8mo ago
heh alright, i do gotta hop off for a bit in like an hour but ill be around most of the night
sebt
sebt8mo ago
ok nice one thank you
Stan
Stan8mo ago
but yeah thats fine bro, dont sweat it, we've all been there and it is hard when you just get started
sebt
sebt8mo ago
yea ive made a new class in my main program in which im attempting to implement the functions that will cycle through the file and output the answers based on the users questions do i make a function within this class that ill then implement the necessary loops into in order for it to successfully check the users input and then compare that to the data in the file
Angius
Angius8mo ago
What's in the screenshot is quite literally all I have The input in the terminal is my entire input
sebt
sebt8mo ago
so u have to input: it's raining cats and dogs in order for it to return unga bunga ohh because the code says the input has to fulfill all the parameters present in the file so u have to input cats and dogs in some sort of way to get unga bunga returned
Stan
Stan8mo ago
yeep so if u input stuff that doesnt match, it wont work. if u put in both inputs it should but i dont think it helpful to paste code you dont understand. linq is very magical, but if you cant implement it without it, youre missing essentials
sebt
sebt8mo ago
yeah fair enough so i was trying to do this without linq do i approach it in a way that basically uses for loops and then put that insdie a method and then use that method to check user input? because i have no clue how to do it
Stan
Stan8mo ago
yeah sounds about right, or foreach loops for convinience i can prototype it for you if its too hard
sebt
sebt8mo ago
if that wouldnt be too much of an inconvenience i would seriously appreciate just like a draft or basic frame for it
Stan
Stan8mo ago
just to clarify, when both params are in our string, we want to console.writeline .Question right? im already writing it lel
sebt
sebt8mo ago
yeah haha and so it would be like when paramx and paramy are in string, print question and its corresponding answer 1 and then if paramz and paramq are in string print qusetion and its corresponding answer 2 but i will store both the q and a in a json file together then output it as 1 or output it as 2 but output them both together
Stan
Stan8mo ago
public static void Main()
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);
var input = Console.ReadLine ?? "";
var matchedQuestion = GetMatchedQuestion(input, data);

if (matchedQuestion == null)
{
Console.WriteLine("Oopsie floopsie, not a question we know the answer to");
}

// Do stuff with our matchedQuestion
}

// Params are input and data so we can access it in the method (can't access variables scoped to Main() otherwise)
// Returns QuestionChooser that matches, or null if nothing matches
public static QuestionChooser GetMatchedQuestion(string input, List<QuestionChooser> data)
{
// Outer loop we go over all our QuestionChoosers
foreach (QuestionChooser qs in data)
{
// We create a counter for the inner loop to see track how many Params of this specific questionchooser match
// Because we need all elements to match rather than just one of the params
int innerMatchCount = 0;

// Then we create the inner loop to actually check the params
foreach (string qsParam in qs.Params)
{
if (input.Contains(qsParam))
{
innerMatchCount++; // This is the same as innerMatch = innerMatch + 1;
}

// Now we validate that all parameters were found by checking matchCount against the amount of params
// If all params were found, we know we have a match and we can return the QuestionChooser
// that we found back to Main() to handle it there
if (qs.Params.Length == innerMatchCount)
{
return qs;
}
// else keep looping until we found something
}

}

// We looped everything and didnt find anything, so we return null
return null
}
public static void Main()
{
var file = await File.ReadAllTextAsync("data.json");
var data = JsonSerializer.Deserialize<List<QuestionChooser>>(file);
var input = Console.ReadLine ?? "";
var matchedQuestion = GetMatchedQuestion(input, data);

if (matchedQuestion == null)
{
Console.WriteLine("Oopsie floopsie, not a question we know the answer to");
}

// Do stuff with our matchedQuestion
}

// Params are input and data so we can access it in the method (can't access variables scoped to Main() otherwise)
// Returns QuestionChooser that matches, or null if nothing matches
public static QuestionChooser GetMatchedQuestion(string input, List<QuestionChooser> data)
{
// Outer loop we go over all our QuestionChoosers
foreach (QuestionChooser qs in data)
{
// We create a counter for the inner loop to see track how many Params of this specific questionchooser match
// Because we need all elements to match rather than just one of the params
int innerMatchCount = 0;

// Then we create the inner loop to actually check the params
foreach (string qsParam in qs.Params)
{
if (input.Contains(qsParam))
{
innerMatchCount++; // This is the same as innerMatch = innerMatch + 1;
}

// Now we validate that all parameters were found by checking matchCount against the amount of params
// If all params were found, we know we have a match and we can return the QuestionChooser
// that we found back to Main() to handle it there
if (qs.Params.Length == innerMatchCount)
{
return qs;
}
// else keep looping until we found something
}

}

// We looped everything and didnt find anything, so we return null
return null
}
thats the general idea. again, this is not good code, ZZZ's solution is way more elegant but it's important that you know what's going on. if you're confused about something, feel free to ask
sebt
sebt8mo ago
thank you so much so this is a way to solve it without using this linq thing
Stan
Stan8mo ago
ill explain the linq solution im a bit too. its kinda chaos rn here lel
sebt
sebt8mo ago
hahaha
Stan
Stan8mo ago
Alright so lets first cover how LINQ kinda works. For now, all you rly gotta know is that it uses some magic under the hood and it's extremely useful to write clean code. Mind, if you need very high performance, it's not always the best, but for most usecases its ok to use. Lets for use .OrderBy() as an example. it basically sorts an array. Using it looks like this: QuestionChooser[] sortedArray = myArray.OrderBy(x => x.Question); This would order your array alphabetically by Question. the x => x threw me off at first too. What it does is roughly the same as a foreach (QuestionChooser x in myArray) { /* sorting logic here */ } loop x is basically the instance we're currently doing stuff with in our loop. You could also call it something other than x like qs then youd have myArray.OrderBy(qs => qs.Question) it's basically just the variable name in the loop, with me so far?
sebt
sebt8mo ago
so is the code here saying something like foreach qs in question, and then using the OrderBy function for each qs
Stan
Stan8mo ago
kinda, except you dont need to do the foreach yourself. OrderBy() takes care of pretty much everything. You just gotta define what you wanna order by, in this case QuestionChooser.Question and the way to do that is by using the arrow like .OrderBy(x => x.Question)
sebt
sebt8mo ago
ah ok so u define what ur ordering inside the orderby by using x=> x.whatistobeordered
Stan
Stan8mo ago
then you get back your array of QuestionChooser, but ordered alphabetically by the values in QuestionChooser.Question yep
sebt
sebt8mo ago
i see
Stan
Stan8mo ago
So if we break down the original linq query to your problem
var question = data.First(q => q.Params.All(p => input.Contains(p)));
var question = data.First(q => q.Params.All(p => input.Contains(p)));
What happens here is data.First() will says we will grab the first thing that matches our conditions. defined inside First() and assign it to our var question
sebt
sebt8mo ago
ok i get that
Stan
Stan8mo ago
q => q.Params.All(...) This says that we're looping over Params in the instance of QuestionChooser we're currently evaluating, and that all conditions must match.
sebt
sebt8mo ago
so its like a foreach loop and it cycles through every parameter?
Stan
Stan8mo ago
yeah exactly its just kind of a shortcut and it does our little innerMatchCount thing internally
Angius
Angius8mo ago
It checks if .All() elements from the collection satisfy the given condition
Stan
Stan8mo ago
finally we have p => input.Contains(p) which again takes the parameter provided by All() which was iterating p.Params and we check if input contains the specific param under the hood, .All and .Contains returns a bool to the caller (which is the linq query wrapping it) makes sense kinda?
sebt
sebt8mo ago
yep makes sense
Stan
Stan8mo ago
awesome
sebt
sebt8mo ago
although im not sure if im gonna use it over the non-linq version for this program
Angius
Angius8mo ago
It shows up well with simple numbers
Stan
Stan8mo ago
yeah thats fine, its a lot of compressed stuff and when you're new its hard enough to read code at all so but its certainly good to add in your toolkit down the line
sebt
sebt8mo ago
oh for sure
MODiX
MODiX8mo ago
Angius
REPL Result: Success
var nums = new[]{ 1, 2, 3, 4, 5, 6 };

new {
FirstDivisibleByThree = nums.First(num => num % 3 == 0),
EveryOddNumber = nums.Where(num => num % 2 != 0),
AreAllLessThanTen = nums.All(num => num < 10),
// and so on
}
var nums = new[]{ 1, 2, 3, 4, 5, 6 };

new {
FirstDivisibleByThree = nums.First(num => num % 3 == 0),
EveryOddNumber = nums.Where(num => num % 2 != 0),
AreAllLessThanTen = nums.All(num => num < 10),
// and so on
}
Result: <>f__AnonymousType0#1<int, IEnumerable<int>, bool>
{
"firstDivisibleByThree": 3,
"everyOddNumber": [
1,
3,
5
],
"areAllLessThanTen": true
}
{
"firstDivisibleByThree": 3,
"everyOddNumber": [
1,
3,
5
],
"areAllLessThanTen": true
}
Compile: 597.827ms | Execution: 124.321ms | React with ❌ to remove this embed.
sebt
sebt8mo ago
this example zzz provided me is so nice
Accord
Accord8mo 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
More Posts