Compare and calculate first, second, and third place - c#

I am trying to figure out the most efficient way to calculate first, second, and third place for a simple C# program in which the purpose is to find the winner, 2nd place, and 3rd place and show their names accordingly however, my code seems way to large for such a simple task. I am new and I an using If statements to complete the required calculation but, I know there is a better way. Can someone enlighten me?
Here is my current code and where I stopped after realizing the amount a code this is going to take.
private void calculateButton_Click(object sender, EventArgs e)
{
// Define Name and Time Variables
string runnerone = runnerOneNameTextBox.Text; // Runner One Name
string runnertwo = runnerTwoNameTextBox.Text; // Runner Two Name
string runnerthree = runnerThreeNameTextBox.Text; // Runner Three Name
double runnerOneTime = double.Parse(runnerOneTimeTextBox.Text); // Runner One Time
double runnerTwoTime = double.Parse(runnerTwoTimeTextBox.Text); // Runner Two Time
double runnerThreeTime = double.Parse(runnerThreeTimeTextBox.Text); // Runner Three Time
//-------------------------------------------------------------------------
// Start of the If statement to calculate who is first, second, and third.
//-------------------------------------------------------------------------
// FIRST PLACE CODE:
if (runnerOneTime > runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner One is greater than everyone
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
}
else if (runnerOneTime == runnerTwoTime && runnerOneTime > runnerThreeTime) // Runner one is equal to runner two
{
firstPlaceLabel.Text = runnerOneNameTextBox.Text;
firstPlaceLabel.Text = runnerTwoNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerOneNameTextBox.Text;
firstPlaceTrophyLabel.Text = runnerTwoNameTextBox.Text;
}
else if (runnerOneTime > runnerTwoTime && runnerOneTime == runnerThreeTime)
}
}
}

You have a list of three runners, so let the .NET list sorting functionality come to your rescue:
private class RunnersAndTimes
{
public string Name {get};
public double Time {get};
public RunnersAndTimes(string name, double time)
{
Time = time;
Name = name;
}
}
...
private void calculateButton_Click(object sender, EventArgs e)
{
var runnersAndTimes = new List<RunnersAndTimes> {
new RunnersAndTimes(runnerOneNameTextBox.Text,
double.Parse(runnerOneTimeTextBox.Text)),
new RunnersAndTimes(runnerTwoNameTextBox.Text,
double.Parse(runnerTwoTimeTextBox.Text)),
new RunnersAndTimes(runnerThreeNameTextBox.Text,
double.Parse(runnerThreeTimeTextBox.Text))
};
var orderedRunners = runnersAndTimes.OrderBy(runner => runner.Time).ToList();
firstPlaceLabel.Text = orderedRunners[0];
secondPlaceLabel.Text = orderedRunners[1];
thirdPlaceLabel.Text = orderedRunners[2];
}

Related

List resetting when adding new items (Edited title to reflect actual issue)

Original Title: Get-Set to add Object w/multiple properties into a list C#
Edit: I had originally thought the issue was in setting up properties for the list objects, when it was an issue with regards to where I had initialized the list in my main code class.
Original Post:
New to coding, taking a C# course. We're working on encapsulation and get:set/properties.
The assignment says that we have to build a class that creates a die with an input number of sides, and "roll" the die for a random number. Easy!
In a second class, we have to build a function to add or remove any number of dice to the pool, and then roll them all for a result.
I'm assuming they want the dice pool to be a list that is private.
My logic going in was to create the single OneDie class, and then using a xDy notation in the main program prompt to add x number of die with y sides to the list. (ie: add 2d6)
I've built an AddDie function that should do that, but when I check my list count after it's done, the count is 0. The private list (_dicePool) seems to be re-setting to zero every time I try to add a new object to the list. I suspect I'm not building my property DicePool's get/set functionality correctly, but I'm not sure how to call my 2-parameter AddDice function from inside the DicePool{set}, or even if that's the approach I should take.
Assuming the list should be private, am I missing something to permanently add new objects to the list?
Edit to add: OR, would it be better to create a ManyDice object? But how do I build this.Sides and this.Roll from the OneDie object?
Here's my code that's applicable to adding objects (dice) to the list (dicepool).
class ManyDice
{
private List<OneDie> _dicePool = new List<OneDie>();
//What I think I might have to do:
public List<OneDie> DicePool
{
get
{
return this._dicePool;
}
set
{
//???????????? how do I call AddDice, when I need 2 parameters for it?
}
}
public void AddDie(int number, int sides)
{
for (int i = 0; i < number; i++)
{
this.dicePool.Add(new OneDie(sides));
}
}
}
class OneDie
{
private int _sides, _rolledValue;
public int Sides
{
get
{
return this._sides;
}
set
{
this._sides = value;
}
}
public int RollValue
{
get
{
return this._rolledValue;
}
set
{
this._rolledValue = value;
RollIt(value);
}
}
public OneDie()
{
}
public OneDie(int sides)
{
this.Sides = sides;
this.RollValue = sides;
}
private int RollIt (int sides)
{
Random random = new Random((int)DateTime.Now.Ticks);
return random.Next(1, (sides + 1));
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Let's roll some dice!");
Console.WriteLine("Please enter the number of dice you want to roll in the following format:");
Console.WriteLine("xdy, where \"x\" is the number of dice you want and \"y\" is how many sides they have.");
Console.WriteLine("Example: 2d6 is 2 6-sided dice. Perfect for playing Catan! (or Monopoly)");
Console.WriteLine("Please limit your dice to d4, d6, d8, d10, d12, d20");
Console.WriteLine("To add a die, type \"add xdy\" to add x number of y sided dice.");
Console.WriteLine("To remove a die, type \"remove xdy.\" to remove x number of y sided dice.");
Console.WriteLine("Type \"dice\" to see a list of all the dice in the pile.");
Console.WriteLine("Type \"roll\" to roll all the dice and see the results!");
Console.WriteLine("Type \"clear\" to clear all the dice and start agin!");
Console.WriteLine("Type \"exit\" to exit program\n");
PlayDice();
Console.ReadKey();
}
static void PlayDice()
{
do
{
string[] xDy = null;
int numberOfDice = 1;
int numberOfSides=1;
Console.WriteLine("\nEnter your command:");
string option = Console.ReadLine();
option = option.ToLower().Trim();
string[] words = option.Split(' ');
string command = words[0];
//CheckCommand(command);
if (words.Length > 1)
{
xDy = words[1].Split('d');
numberOfDice = int.Parse(xDy[0]);
numberOfSides = int.Parse(xDy[1]);
}
ManyDice die = new ManyDice();
if (command == "exit")
{
Console.WriteLine("Thank you, play again, soon!");
break;
}
else if (command == "add")
{
//numberOfSides=CheckDice(numberOfSides);
die.AddDie(numberOfDice, numberOfSides);
Console.WriteLine("You have {0}ed {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "remove")
{
Console.WriteLine("You have {0}d {1} {2}-sided dice.", command, numberOfDice, numberOfSides);
}
else if (command == "dice")
{
Console.WriteLine("These are your dice:");
die.Display();
}
else if (command == "roll")
{
Console.WriteLine("Here is your roll:");
}
else if (command == "clear")
{
Console.WriteLine("All dice have been cleared.");
}
} while (true);
}
static int CheckDice(int sides)
{
List<int> check = new List<int> {4,6,8,10,12,20};
while (!check.Contains(sides))
{
Console.WriteLine("{0}-sided dice are not available.\nPlease enter 4,6,8,10,12 or 20");
sides = int.Parse(Console.ReadLine());
}
return sides;
}
static string CheckCommand(string instructions)
{
List<string> check = new List<string> { "add", "remove", "dice", "roll","clear", "exit" };
while (!check.Contains(instructions))
{
Console.WriteLine("Command not recognized.\nPlease enter \"add\", \"remove\", \"dice\", \"roll\",\"clear\", or \"exit\"");
instructions = Console.ReadLine();
}
return instructions;
}
}
New Answer based on comments and updated question:
The line ManyDice die = new ManyDice(); is wiping your dice list clean every loop through your program. It's replacing your variable with a new instance of the class, with a fresh list and all.
Simply move that line before the start of the loop:
before the line do {
and then every iteration will use the same instance of ManyDice, and will all share the variable die, without overwriting it.
OLD ANSWER: From what I can see, your program only runs once. And then you need to start it again to put in another dice. Your main function only asks for input once. Whenever you start the program again, all the memory used in the program gets cleared. Unless I’m missing something, that is why your list continues to be reset. You’re actually running a completely new program the next time you try to add dice. So it has no knowledge of the previous runs.
One solution is to say (pseudo code)
While (running) {
// what you have now
if (option == “done”) running = false;
if (option == “roll”) // roll all dice.
}
This will keep prompting the user for commands until they type done. And it remains the same program so that you don’t lose the data from earlier commands.
Update based on comment: you’re recreating the ManyDice instance on each iteration, effectively starting from scratch. Save the instance outside the while loop and then reuse it.
Hint:
Your rolling should probably be done by manyDice.RollAll() And maybe should return a List of RollResults.

Validation Returns False, Then Continues Program Regardless [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Edit add: The problem I was given amounts to making use of a text file that contains 18 differing account numbers. I'm given the option of making the program read it to an array or a List<>. Then the program should allow a user to input a number and determine if it matches an entity in the array/List<>, displaying that it's valid/invalid.
It took me a fair while to get my code to work correctly. Now, I don't mind that a bad input validation returning false is followed by the latter methods being run through, thus producing the second popup. It's rather annoying at times, however. It works fine, like I said, but I'd like to find out if there's a way to make it stop running through the rest if the validation returns false.
private void ReadAccNums(int[] accountNumArray)
{
// Try-catch to prevent file error issues.
try
{
// Increment num var.
int num = 0;
// Open ChargeAccounts.txt file.
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
// Read account numbers into array.
while (num < accountNumArray.Length && !accNumsFile.EndOfStream)
{
// Put each item into accountNumArray.
accountNumArray[num] = int.Parse(accNumsFile.ReadLine());
num++;
}
// Close file.
accNumsFile.Close();
}
catch (Exception ex)
{
// Display error message.
MessageBox.Show(ex.Message);
}
}
// Method to handle TextBox input
// validation.
private bool InputIsValid(ref int accNum)
{
// Flag to make sure input is good.
bool inputValid = false;
// Get and validate accountNumbersAccessTextBox input.
if (int.TryParse(accountNumberAccessTextBox.Text, out accNum))
{
// Did we get this far? Confirm input validation.
inputValid = true;
}
// Display error message for accNum.
else
{
MessageBox.Show("Please input a non-decimal, seven digit number" +
" for the account number.");
// Reset Focus to accountNumbersAccessTextBox.
accountNumberAccessTextBox.Focus();
}
// Return result.
return inputValid;
}
// Method to find out if input
// has a match in ChargeAccounts.txt.
private int AccNumSearch(int accNum,
int[] accountNumArray)
{
// Bool flag for matching accNum.
bool accNumFound = false;
// Index var.
int num = 0;
// Position of Sequential Search.
int position = -1;
// Get input from TextBox.
if (InputIsValid(ref accNum))
{
// Read through array to find
// matching accNum.
while (!accNumFound && num < accountNumArray.Length)
{
if (accountNumArray[num] == accNum)
{
// Found a match? Yay! Access granted!
accNumFound = true;
position = num;
}
num++;
}
}
// Return.
return position;
}
// Method to determine whether input
// matches an account number.
private bool AccNumMatch(int[] accountNumArray,
ref int accNum)
{
// Bool flag to confirm
// matching accNum.
bool accNumMatch = false;
// Got a match? Tell the user.
if (AccNumSearch(accNum, accountNumArray) != -1)
{
accNumMatch = true;
MessageBox.Show("Account number correct. Access granted.");
}
else
{
// No match? Alas.
MessageBox.Show("Account number invalid. Access denied.");
}
// Return.
return accNumMatch;
}
private void accountNumberAccessButton_Click(object sender, EventArgs e)
{
// Declare array to be filled by
// ReadAccNums method.
const int SIZE = 18;
int[] accountNumArray = new int[SIZE];
// Get the account numbers.
ReadAccNums(accountNumArray);
// Var for accNum to ref.
int accNum = 0;
// Is our account number correct?
AccNumMatch(accountNumArray, ref accNum);
}
Your code seems and incredibly verbose approach to:
the user types a number into a textbox
the program checks it's numeric
the program checks it's present in a file
If I was tasked to write such a code I might:
void Login_Click(object sender, EventArgs e){
if(!int.TryParse(accountNumberTextbox.Text, out int seeking)) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
accNumMatch = File.ReadLines("c:\\temp\\accountnumbers.txt").Any(line => line == accountNumberTextbox.Text));
if(accNumMatch) {
MessageBox.Show("Account number correct. Access granted.");
}
else {
MessageBox.Show("Account number invalid. Access denied.");
}
}
because there simply isn't any point in converting the file contents to number and then searching the number; simpler to leave them as strings and compare strings, after making sure what the user entered was a number
And if I used a numericupdown so the user couldn't even enter a non number:
void Login_Click(object sender, EventArgs e){
accNumMatch = File.ReadLines("c:\\temp\\accountnumbers.txt").Any(line => line == accountNumberNumericUpDown.Value.ToString()));
if(accNumMatch) {
MessageBox.Show("Account number correct. Access granted.");
}
else {
MessageBox.Show("Account number invalid. Access denied.");
}
}
YOu can just convert what they entered to text and launch straight into reading the file and looking for a line bearing what they entered
I appreciate you might be learning, so using LINQ is a bit of a cheat, but even so:
void Login_Click(object sender, EventArgs e){
if(!int.TryParse(accountNumberTextbox.Text, out int seeking)) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
accNumMatch = false;
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
while (!accNumsFile.EndOfStream && !accNumMatch)
{
string line = accNumsFile.ReadLine();
accNumMatch = (line == accountNumberTextbox.Text);
}
}
I'll forego lecturing about using/making sure you close and dispose your file readers etc for now ;)
If you have to read a file into an array, you can use System.IO.File.ReadAllLines() as a quick way to read a file. I won't use it here, but you can look it up if you want to see
If you have to read up to X lines from a file, into an array of ints, and then see if any of the ints are the one you seek:
void Login_Click(object sender, EventArgs e){
bool validInput = int.TryParse(accountNumberTextbox.Text, out int seeking);
if(!validInput) {
MessageBox.Show("The account number text does not appear to be numeric");
return;
}
int[] numbers = new int[100];
StreamReader accNumsFile = File.OpenText("ChargeAccounts.txt");
for(int i = 0; i < numbers.Length && !accNumsFile.EndOfStream; i++)
{
string line = accNumsFile.ReadLine();
numbers[i] = int.Parse(line);
}
accNumMatch = false;
foreach(int number in numbers){
if(number == seeking) { //seeking comes from earlier
accNumMatch = true;
break;
}
}
}
You could break these into separate methods. Make a method that takes an input and gives an output:
void Login_Click(object sender, EventArgs e){
int seek = ConvertToAccountNumber(accountNumberTextbox.Text);
if(seek == -1){
MessageBox.Show("Enter a valid number");
return
}
int[] numbers = GetAccountNumbersInFile("ChargeAccounts.txt");
accNumMatch = ArrayContainsNumber(numbers, seek);
}
//this is basically a variation of int.Parse/int.TryParse
public int ConvertToAccountNumber(string s){
bool validInput = int.TryParse(accountNumberTextbox.Text, out int seeking);
if(!validInput)
return -1; //we will use -1 to signify invalid input, because no account number is ever -1
else
return seeking;
}
//File.ReadAllLines can help with this, as can LINQ Select/int parse
public int[] GetAccountNumbersInFile(string p){
int[] numbers = new int[100];
StreamReader accNumsFile = File.OpenText(p);
for(int i = 0; i < numbers.Length && !accNumsFile.EndOfStream; i++)
{
string line = accNumsFile.ReadLine();
numbers[i] = int.Parse(line);
}
}
//there exist helper methods for doing this too, look at the Array class - https://learn.microsoft.com/en-us/dotnet/api/system.array?view=netcore-3.1
public bool ArrayContainsNumber(int[] array, int seeking){
foreach(int number in numbers){
if(number == seeking) {
return true;
}
}
return false;
}
I know why you used ref but you should avoid it. Actually the framework uses out when it parses text to a number and returns a boolean to indiccate the success and a number, but you can easily take the approach that something like string.IndexOf takes - it returns -1 if the needle is not found in the haystack. You haven't learned about exceptions yet (probably) but this would be an opportunity to use them too - throw an exception instead of returning a value if the input data is bad
All in, it's one of the few places where out might be reasonable in your career, so use it if you must (for academicc reasons, but don't use ref - ref is for methods that take a variable in with the intention of using its value before possibly overwriting it with something else. This is an out scenario, where the input variable shouldn't have a value and will be overwritten by the method) but

How to implement in console quiz the removal of an option every t2 seconds (t2<T)

I am new to C# and I am trying to build console quiz.
Here is my problem:
For every option removed I have to reduce one option (let's say the total points are 100).
If one option is removed I need to reduce the total points by 25 (i.e now the total points will be 75).
JSON data:
{
"question": [
{
"level": "Easy",
"cat": "sports",
"description": "Who is the Highest run getter in 2019",
"Option1": "Rohit Sharma",
"Option2": "Virat Kohli",
"Option3": "Kl Rahul",
"Option4": "S Dhawan",
"Answer":"1"
}]
}
Program:
using System;
using System.Timers;
namespace CProgram
{
class EasyQuestion
{
private string mLevel;
private string mCat;
private string mDescription;
private string mOption1;
private string mOption2;
private string mOption3;
private string mOption4;
private string mAnswer;
public string MDescription { get => mDescription; }
public string MOption1 { get => mOption1; }
public string MOption2 { get => mOption2; }
public string MOption3 { get => mOption3; }
public string MOption4 { get => mOption4; }
public string MAnswer { get => mAnswer; }
public string MLevel { get => mLevel; }
public string MCat { get => mCat; }
public static int sQcount=1;
public int sPlayerScore=0;
public int mNoOfQuesAnswerd=0;
static Timer questionTimer = new Timer(60000) ;
private static void QuestionTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("Time up!");
System.Console.WriteLine("Lets Move on to Next Question");
questionTimer.Stop();
}
public EasyQuestion(string level,string cat,string description,string Option1,string Option2,string Option3,string Option4,string Answer)
{
this.mLevel=level;
this.mCat=cat;
this.mDescription=description;
this.mOption1=Option1;
this.mOption2=Option2;
this.mOption3=Option3;
this.mOption4=Option4;
this.mAnswer=Answer;
}
public EasyQuestion()
{
}
public void AskEasyQues(EasyQuestion easyQuestion)
{
System.Console.WriteLine("Here is Your:"+sQcount+" Question:");
System.Console.WriteLine("***********************************");
System.Console.WriteLine("Question is of The Category:"+easyQuestion.MCat);
System.Console.WriteLine("***********************************");
System.Console.WriteLine(easyQuestion.MDescription);
System.Console.WriteLine("--------------------------------------");
System.Console.WriteLine("1:"+easyQuestion.MOption1+" "+"2:"+easyQuestion.MOption2);
System.Console.WriteLine();
System.Console.WriteLine("3:"+easyQuestion.MOption3+" "+"4:"+easyQuestion.MOption4);
System.Console.WriteLine();
questionTimer.Elapsed += QuestionTimer_Elapsed;
questionTimer.Enabled = true;
questionTimer.Start();
System.Console.WriteLine("Enter your Choice:");
/*for (int a = 60; a >= 0; a--)
{
Console.Write("\rGenerating Preview in {0:00}", a);
System.Threading.Thread.Sleep(1000);
} */
string ans=Console.ReadLine();
if(ans==easyQuestion.MAnswer)
{
questionTimer.Stop();
mNoOfQuesAnswerd++;
System.Console.WriteLine();
System.Console.WriteLine("------Well Played Champion!!!!!!-----");
sPlayerScore=sPlayerScore+100;
}
else
{
System.Console.WriteLine();
System.Console.WriteLine("------Wrong Choice Lets Move On--------");
}
System.Console.WriteLine();
System.Console.WriteLine("Press any Key To Continue For Next Question");
Console.ReadLine();
System.Console.WriteLine();
System.Console.WriteLine("----------------------------");
sQcount=sQcount+1;
Console.Clear();
}
}
}
I have a timer of 60 seconds and I have to remove an option every 15 seconds.
Here; I wrote this for you to show you why you can't easily do what you're asking:
static void Main(string[] args)
{
string[] answers = new[] { "answer one", "answer two", "answer three", "answer four" };
Random r = new Random();
int rightAnswer = 2;
Console.Write("\r" + string.Join(", ", answers));
for (int i = 1; i < 60; i++)
{
if (i % 15 == 0)
{
//randomly remove an answer that is not the right one
int a = r.Next(answers.Length);
while (a == rightAnswer || answers[a][0] == ' ') // dont remove the right answer! dont pick an answer that is already blanked
a = r.Next(answers.Length);
answers[a] = new string(' ', answers[a].Length); //replace answer with spaces
//return to the start of the line and overwrite
Console.Write("\r" + string.Join(", ", answers));
}
System.Threading.Thread.Sleep(100);
}
Console.Write("\nQuit");
}
It "works" in that it will remove one option every 1.5 seconds (if you want 15, extend the sleep) but the question cannot be answered on the console. As soon as you put a ReadLine() in there to get the answer, the program will halt waiting at that point until the user puts the answer in. You can take this and work out some other super complicated way of getting the answer in, such as opening a listening port and having the user telnet into the program and submit their answer that way etc...
But truly; have a play and see what me and Chris are saying and then do it in a windows GUI
Timers and consoles do not mix that well. Or really at all. In Console usually you go from one Blocking Input request to the next (ReadLine() and ReadKey()), with the odd phase of processing in between.
It is possible to poll input without blocking in a console, but that is a pretty advanced topic. And if you ever need to do that, chances are you should not have a console programm in the first place.
The rest is just clear+reprint or setting the cursor back and overwriting. Personally I prefer the clean+rewrite method for such a case.
Counting of the time can be done with DateTime.Now and .AddSeconds(). But I can only repeat, that with Windows Forms or another GUI this would be incredibly trivial. Would be just adding a timer and setting one button to hidden.

How to Pass Values Between Pages?

I am doing Airline Reservation System using GUI with ASP.NET in C#.
What I want is assign seats for user, after a user assign that seats, that seat cannot be assigned by others again. I try to use increment do this but instead of 1+1 = 2(that means seat number 2 is the next to be assigned), the system gives me 1+1=11. How can I do what I want?
I have 5 interfaces for this, and I need this assigned value stored in whole running process.
This is my code for the reservation button, I have 2 for it, First Class and Economy Class. Only 5 seats for First Class and 15 seats for Economy Class.
How can I do ?
protected void Button1_Click(object sender, EventArgs e)
{
Session["seats"] = "First Class";
if (firstseatnum > 5)
{
MessageBox.Show("Sorry, the first class seats was fully booked. Can you change to economy class?");
Response.Redirect("reservation.aspx");
}
else
{
++firstseatnum;
totalseatnum1 = Convert.ToInt32(firstseatnum+seatnum);
Response.Redirect("~/information.aspx?firstseatnum="+firstseatnum+"&seatnum="+totalseatnum1);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
Session["seats"] = "Economy Class";
if (economyseatnum > 20)
{
MessageBox.Show("Sorry, the economy class seats was fully booked. Can you change to first class?");
Response.Redirect("reservation.aspx");
}
else
{
++economyseatnum;
totalseatnum2 = Convert.ToInt32(economyseatnum + seatnum);
Response.Redirect("information.aspx?economyseatnum=" + economyseatnum + "&seatnum="+totalseatnum2);
}
}
Please help me, thank you.
There are several ways to do it:
Query
// Set
var myVariable = "MyData";
Response.Redirect("/NextPage?MyVariable=" + myVariable);
// Get
var data = Request.QueryString["MyVariable"];
Cookie
// Set
var cookie = new HttpCookie("MyVariable");
cookie.Value = "NyData";
Response.Cookies.Add(cookie);
Response.Redirect("/NextPage");
// Get
var data = Request.Cookies["MyVariable"].Value;
Session
// Set
Session["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Session["MyVariable"];
Application (Store Entire Process)
// Set
Application["MyVariable"] = "MyData";
Response.Redirect("/NextPage");
// Get
var data = Application["MyVariable"];
Also check CodeProject article to see more examples and detailed explanation.
Presumably seatnum is a string.
If so, try
totalseatnum1 = firstseatnum + Convert.ToInt32(seatnum);
and
totalseatnum2 = economyseatnum + Convert.ToInt32(seatnum);

Program Design Idea c#

I need some idea for the Design of the following Program/Function.
My Program calculates Prices for Tools.
Every Tool has a Diameter and a List of Productionsteps to build this tool.
To get the Production Steps the program reads a XML File with 56 Productionsteps at the begin and creates an object for every Step. After the Creation it adds that object in a List.
The Konstruktor of the Tool knows what Steps are required to build the tool and get them out of the List of the Main Program and adds them to the List of the Tool.
Pseudo Code:
main.cs
List<ProductionStep> listOfAllProductionstep = readAllPS(../pfad/);
Tool abc = new Tool();
tool.cs
private List<ProductionStep> psList;
public Tool() {
foreach (ProductionStep ps in listOfAllProductionstep) {
switch(ps.Name) {
case "Abc":
psList.Add(ps);
break;
...
}
}
}
The Problem is now, each of the 56 Productionstep has it own formular to calculate the cost for this step.
My first idea was to use a Switch Case construct in the calculatePrice Function of the tool. But i have to check every step with the 56 availiable Steps to get the Right Formular for this step.
Now my Question. Is there a better solution to this?
Mabe you are looking for something like this:
class ProductionStep
{
public string name;
public decimal calculatCosts()
{
return 100;
}
}
List<ProductionStep> listOfAllProductionstep;
private void button5_Click(object sender, EventArgs e)
{
List<ProductionStep> psList = new List<ProductionStep>();
psList.Add(listOfAllProductionstep.Find(o => o.name == "Abc"));
psList.Add(listOfAllProductionstep.Find(o => o.name == "Def"));
decimal totalCosts = 0;
foreach (ProductionStep ps in psList)
totalCosts += ps.calculatCosts();
}

Categories

Resources