C
C#13mo 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
Angius13mo 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
sebtOP13mo ago
hmm i think i understand
Stan
Stan13mo 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
sebtOP13mo ago
surely this will also be alot of hardcoded lines tho also?
Angius
Angius13mo ago
No Just those 3
Stan
Stan13mo ago
how come
Angius
Angius13mo ago
Store data in a json file
MODiX
MODiX13mo ago
Angius
Store data in a json file
React with ❌ to remove this embed.
sebt
sebtOP13mo 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
Stan13mo ago
thats why you use an array instead owo
sebt
sebtOP13mo 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
Angius13mo 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
sebtOP13mo ago
so the top code isnt in visual studio it is in a json file
Angius
Angius13mo ago
It is a part of the project, yes
sebt
sebtOP13mo 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
Angius13mo ago
Like I wrote Place the file next to your .csproj Mark it to copy always or copy if newer Done
sebt
sebtOP13mo ago
what do i paste it into a new text file then put that next to the csproj in the folder
Angius
Angius13mo 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
sebtOP13mo ago
but when i psate it into vs it comes up with a load of errors
Angius
Angius13mo ago
Like?
sebt
sebtOP13mo ago
No description
sebt
sebtOP13mo ago
bunch of syntax eorrs
Angius
Angius13mo ago
The JSON data is it's own JSON file
sebt
sebtOP13mo ago
yeah how do i do that
Angius
Angius13mo ago
Make a file?
sebt
sebtOP13mo ago
yh do i put it in the same folder as my consoleapp is in
Angius
Angius13mo ago
Yes As I said already, next to the .csproj
sebt
sebtOP13mo ago
ok done but now its sayins jsonserializer dosent exist and Question coudlnt be foud
Angius
Angius13mo ago
Use quick fixes to import the necessary namespace And, right, you will need to create the Question class Or a record
sebt
sebtOP13mo ago
ok i used quick fixes now its saying object doesnt contain a definition for First and theres no quick fixes that solveit
Angius
Angius13mo ago
Quick fixes again You need System.Linq namespace
sebt
sebtOP13mo ago
i dont understand wdym
Angius
Angius13mo ago
Use the quick fixes on First
sebt
sebtOP13mo ago
it only says convert to top level statemetns
Angius
Angius13mo 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
sebtOP13mo ago
so shall i make a new class for First
Angius
Angius13mo ago
No, why? Include the namespace
sebt
sebtOP13mo ago
what do you mean inclued the namespac
Angius
Angius13mo ago
using System.Linq;
sebt
sebtOP13mo ago
yeah ive typed that but visual studio greys it out and says its unnecessary
Angius
Angius13mo ago
Show your code
Stan
Stan13mo ago
and your error
sebt
sebtOP13mo ago
do u want it in a screenshot or typed out
Angius
Angius13mo ago
$code
MODiX
MODiX13mo 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
Angius13mo ago
And maybe a screenshot of the errors
sebt
sebtOP13mo 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
Angius13mo ago
Well
sebt
sebtOP13mo ago
No description
Angius
Angius13mo ago
Your Question has no properties
sebt
sebtOP13mo ago
yeah i know
Angius
Angius13mo ago
And you're trying to access its Params and Question properties Can't access what doesn't exist
sebt
sebtOP13mo ago
but i thought they were stored in the json file
Stan
Stan13mo ago
hwck is Params anyway, i thought it was some json thing i didnt know about for a moment
Angius
Angius13mo ago
The json file just stores the data
sebt
sebtOP13mo ago
ok
Stan
Stan13mo ago
yeah, we're in C# baby, everything needs types here
sebt
sebtOP13mo ago
so what do i do and also how do i fix the First error
Angius
Angius13mo ago
* The record has no properties * That's an issue * How do I fix that issue? Take a guess
Stan
Stan13mo ago
Gotta add the Params and Question properties to your record so c# knows how to interpret your json file
Angius
Angius13mo 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
sebtOP13mo ago
oh so it like converts it
Stan
Stan13mo 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
sebtOP13mo ago
so whats the point of storing it in a json file if it needs to be redefined in c#
Angius
Angius13mo ago
Because it's easier?
Stan
Stan13mo ago
you only define the properties in c# rather than all the actual questions and answers
sebt
sebtOP13mo ago
ohh
Stan
Stan13mo ago
if you have a lot of data, this will save a lot of hardcoded crap
sebt
sebtOP13mo ago
yeah
Stan
Stan13mo ago
plus json is used all over, its very useful to learn it, even if this particular application doesnt rly "need" it
Angius
Angius13mo 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
sebtOP13mo ago
so how do i define the properties of the data in my json file inside my question record
Angius
Angius13mo ago
You wanted to avoid hardcoding the data in your source code That's how
MODiX
MODiX13mo 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
Angius13mo ago
Refer to this
sebt
sebtOP13mo ago
what so like this
public record QuestionChooser(string ParamOne, string ParamTwo, string Question);
public record QuestionChooser(string ParamOne, string ParamTwo, string Question);
Stan
Stan13mo ago
that might work with modern c#? im not sure
Angius
Angius13mo 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
sebtOP13mo ago
so
public record QuestionChooser(string[] Params, string Question);
public record QuestionChooser(string[] Params, string Question);
?
Angius
Angius13mo ago
Yep
Stan
Stan13mo ago
yeah thatll do :3
sebt
sebtOP13mo ago
so how do i fix this error with data.First
Stan
Stan13mo ago
you still get it?
sebt
sebtOP13mo ago
yh
Stan
Stan13mo ago
might need to make it a List<string> instead of array
Angius
Angius13mo ago
Nah .First() works on IEnumerable
sebt
sebtOP13mo 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
Angius13mo 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
Stan13mo ago
man this third person debugging shit is weird, feels like a skill on its own
sebt
sebtOP13mo ago
i had to change the name of the record to QuestionChooser because the string parameter was called Question btw
Angius
Angius13mo ago
Ah
Stan
Stan13mo ago
5head
Angius
Angius13mo ago
Maybe that was the issue, yeah Good thinking
sebt
sebtOP13mo ago
but im getting more errors now i changed var to list haha it says data is already defined
Angius
Angius13mo ago
Do you have another variable named data somewhere?
sebt
sebtOP13mo 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
Angius13mo 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
sebtOP13mo ago
no thats in teh code above
Angius
Angius13mo ago
Show your code
sebt
sebtOP13mo 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
Stan13mo ago
yeah you have two variables called data cant do that
MODiX
MODiX13mo 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
Angius13mo ago
It was named question Why'd you rename it?
sebt
sebtOP13mo ago
wtf my bad i didnt mean to idk how that happened
Stan
Stan13mo ago
no stress lol
sebt
sebtOP13mo ago
im still getting this error now though even after renaming it back to question and having it as List<QuestionChooser> question = ...
Angius
Angius13mo ago
Because it's a QuestionChooser now Not a list anymore You can just use var tbh
sebt
sebtOP13mo ago
ok i put it back to var
Stan
Stan13mo 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
sebtOP13mo ago
yeah i gotchu but the compiler is still giving me the same error as before
Stan
Stan13mo ago
what error was that?
sebt
sebtOP13mo 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
Angius13mo ago
Show code again
sebt
sebtOP13mo 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
Stan13mo ago
dafuq lol
Angius
Angius13mo ago
This should, by all accounts, work
Stan
Stan13mo 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
sebtOP13mo ago
yeah data.first(); still the same error
Stan
Stan13mo ago
if you hover over "data" what does it say the type is
sebt
sebtOP13mo ago
object?
Stan
Stan13mo ago
lolwhy
Angius
Angius13mo ago
what It has no right to be object?
Stan
Stan13mo 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
sebtOP13mo ago
No description
sebt
sebtOP13mo ago
i dont know what to do lol
Stan
Stan13mo ago
ok fuck this im booting into windows lol this is insane
sebt
sebtOP13mo ago
haha
Angius
Angius13mo ago
Wait Crazy theory Did the quick fixes on JsonSerializer perhaps create a new class named JsonSerializer?
Stan
Stan13mo ago
ohhhh
Angius
Angius13mo ago
Do you have any other files in the project, any other classes?
sebt
sebtOP13mo ago
yeah it did
Stan
Stan13mo ago
thats gotta be it hahaha
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
i didnt see the using statement i think
Angius
Angius13mo ago
Ah Yeah delete that
sebt
sebtOP13mo ago
the entire class> ?
Angius
Angius13mo ago
The whole file
Stan
Stan13mo ago
the entire JsonSerializrr file not ur actual code
sebt
sebtOP13mo ago
ok done it
Angius
Angius13mo ago
Now, JsonSerializer will be highlighted in red Use quick fixes
sebt
sebtOP13mo ago
No description
Angius
Angius13mo ago
And pick the fix that says to include the required namespace Or include the namespace manually using System.Text.Json;
sebt
sebtOP13mo ago
ok done it fixed it now im getting another error but for questionchooser
sebt
sebtOP13mo ago
No description
Angius
Angius13mo ago
Becase the property is Question Not QuestionChooser
Stan
Stan13mo 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
sebtOP13mo ago
ohh
Angius
Angius13mo ago
No description
Angius
Angius13mo ago
Works on my machine
sebt
sebtOP13mo 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
Stan13mo ago
yay thats gooder
Angius
Angius13mo ago
Is the file copied? Right-click it, open its properties Select copy if newer or copy always
Stan
Stan13mo 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
sebtOP13mo ago
where do i find copy if newer im on windows 11
Stan
Stan13mo ago
vscode or vs2022
sebt
sebtOP13mo ago
what can i not do it from properties
Stan
Stan13mo ago
what code editor do you use? visual studio 2022 or visual studio code
sebt
sebtOP13mo ago
visual studio 2022
Stan
Stan13mo 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
Angius13mo ago
The json file should be there in the solution explorer
Stan
Stan13mo ago
there youll be able to set it. i dont remember what the specific property is called tho..
sebt
sebtOP13mo ago
its in the solution explorer
Stan
Stan13mo ago
but its one of em, it opens a list that lets u pick what happens with the file
sebt
sebtOP13mo ago
No description
sebt
sebtOP13mo ago
i think if this is the solution explorer
Stan
Stan13mo ago
nah its gotta be on the left or right where u open your files bro this is hard xD
sebt
sebtOP13mo ago
here ???
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
nah it should basically be a file in your project leme fimd a screenshot
sebt
sebtOP13mo ago
k ty
Stan
Stan13mo ago
this thing it should be in that list alongside program.cs
sebt
sebtOP13mo ago
where what thing i dont think the image came thru
Stan
Stan13mo ago
oh
sebt
sebtOP13mo ago
ah ok
Stan
Stan13mo ago
No description
sebt
sebtOP13mo ago
so shall i set to copy if newer
Stan
Stan13mo 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
sebtOP13mo ago
ok i set to copy if newer and im still getting the same error lol wtf
Stan
Stan13mo 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
sebtOP13mo ago
wheres the bin/debug fodler
Stan
Stan13mo ago
rightclick ur project and "open containing folder" or something similar in there should be the bin folder, in that the debug folder
sebt
sebtOP13mo ago
yh its in there
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
and your code also says data.json right?
sebt
sebtOP13mo ago
yeah
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
and what was the error exactly?
sebt
sebtOP13mo ago
or is the txt
Stan
Stan13mo ago
ihh
sebt
sebtOP13mo ago
not making it work
Stan
Stan13mo ago
yeah txt bad
sebt
sebtOP13mo 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
Stan13mo ago
first of all, in windows explorer u wanna enable show extensions
sebt
sebtOP13mo ago
how do i do that
Stan
Stan13mo 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
sebtOP13mo ago
yeah ok i gotchu
Stan
Stan13mo ago
then rename the file in ur project root (not bin/debug) then remove the wonky file from ur project
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
rightclick project, add file existing file and select the proper renamed file
sebt
sebtOP13mo ago
wait so i renamed the file now its a json actually
Stan
Stan13mo ago
yep heh
sebt
sebtOP13mo ago
then where do i remove the file
Stan
Stan13mo 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
sebtOP13mo ago
wait my solution explorer just disappeared how do i access it again
Stan
Stan13mo ago
is it tabbed or did u click x
sebt
sebtOP13mo ago
nvm i got it
Stan
Stan13mo ago
alright
sebt
sebtOP13mo 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
Stan13mo ago
yeah, been there lol
sebt
sebtOP13mo ago
now im getting anotha error
Stan
Stan13mo ago
whats the error
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
alright thats good, thats just json syntax being fucked print ur json again please
sebt
sebtOP13mo ago
wym
Stan
Stan13mo ago
theres an error in your json file basically so it cant parse it
sebt
sebtOP13mo ago
No description
Stan
Stan13mo ago
line 1 shouldnt say data.json thats why it cant read it
sebt
sebtOP13mo 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
Stan13mo 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
sebtOP13mo ago
ok so the code runs now
Stan
Stan13mo ago
ayy nice
sebt
sebtOP13mo 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
sebtOP13mo ago
No description
sebt
sebtOP13mo 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
Stan13mo ago
its because First() must have something otherwise it crashes try FirstOrDefault() then it will return null instead of crash
sebt
sebtOP13mo ago
firstordefault gives me this error when i input something
Stan
Stan13mo ago
but you would have to do if (question == null) Console.WriteLine("no match") or something along those lines
sebt
sebtOP13mo ago
No description
Stan
Stan13mo 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
sebtOP13mo ago
i have no clue hahaa
Stan
Stan13mo ago
hehe fair
sebt
sebtOP13mo ago
but im this far i really want to make it work
Stan
Stan13mo ago
yeah of course
sebt
sebtOP13mo ago
using these ideas you know
Stan
Stan13mo 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
sebtOP13mo ago
fair enough
Stan
Stan13mo 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
sebtOP13mo 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
Stan13mo ago
alright, do you know how arrays and loops work?
sebt
sebtOP13mo ago
yeah
Stan
Stan13mo 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
sebtOP13mo ago
i have used classes and records before yeah in the code bascially
Stan
Stan13mo 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
sebtOP13mo ago
ok there are 2 parameters for each question btw essentially 8x4 questions that can be asked
Stan
Stan13mo ago
right, but lets try to stay focused on the scope we're in or even simple processes get confusing
sebt
sebtOP13mo ago
ok my bad
Stan
Stan13mo ago
well its fine, just trying to communicate my way of thinking
sebt
sebtOP13mo ago
yh i gotchu all good
Stan
Stan13mo 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
sebtOP13mo ago
ok niec and the code will automatically read every instance in params from the json file?
Stan
Stan13mo ago
yep because we're looping over everything
sebt
sebtOP13mo 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
Stan13mo ago
once you get the results, it depends what you wanna do with it really
sebt
sebtOP13mo ago
yeah
Stan
Stan13mo 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
sebtOP13mo ago
yeah that makes sense
Stan
Stan13mo 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
sebtOP13mo 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
Stan13mo ago
heh alright, i do gotta hop off for a bit in like an hour but ill be around most of the night
sebt
sebtOP13mo ago
ok nice one thank you
Stan
Stan13mo ago
but yeah thats fine bro, dont sweat it, we've all been there and it is hard when you just get started
sebt
sebtOP13mo 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
Angius13mo ago
What's in the screenshot is quite literally all I have The input in the terminal is my entire input
sebt
sebtOP13mo 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
Stan13mo 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
sebtOP13mo 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
Stan13mo ago
yeah sounds about right, or foreach loops for convinience i can prototype it for you if its too hard
sebt
sebtOP13mo ago
if that wouldnt be too much of an inconvenience i would seriously appreciate just like a draft or basic frame for it
Stan
Stan13mo ago
just to clarify, when both params are in our string, we want to console.writeline .Question right? im already writing it lel
sebt
sebtOP13mo 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
Stan13mo 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
sebtOP13mo ago
thank you so much so this is a way to solve it without using this linq thing
Stan
Stan13mo ago
ill explain the linq solution im a bit too. its kinda chaos rn here lel
sebt
sebtOP13mo ago
hahaha
Stan
Stan13mo 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
sebtOP13mo ago
so is the code here saying something like foreach qs in question, and then using the OrderBy function for each qs
Stan
Stan13mo 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
sebtOP13mo ago
ah ok so u define what ur ordering inside the orderby by using x=> x.whatistobeordered
Stan
Stan13mo ago
then you get back your array of QuestionChooser, but ordered alphabetically by the values in QuestionChooser.Question yep
sebt
sebtOP13mo ago
i see
Stan
Stan13mo 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
sebtOP13mo ago
ok i get that
Stan
Stan13mo 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
sebtOP13mo ago
so its like a foreach loop and it cycles through every parameter?
Stan
Stan13mo ago
yeah exactly its just kind of a shortcut and it does our little innerMatchCount thing internally
Angius
Angius13mo ago
It checks if .All() elements from the collection satisfy the given condition
Stan
Stan13mo 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
sebtOP13mo ago
yep makes sense
Stan
Stan13mo ago
awesome
sebt
sebtOP13mo ago
although im not sure if im gonna use it over the non-linq version for this program
Angius
Angius13mo ago
It shows up well with simple numbers
Stan
Stan13mo 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
sebtOP13mo ago
oh for sure
MODiX
MODiX13mo 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
sebtOP13mo ago
this example zzz provided me is so nice
Accord
Accord13mo 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