How to only run methods when called? - c#

I have a bunch of code below. However, I am hitting some bugs because the methods Move() and Genius() are running logic too much. I only want to two methods to run if they are being called by the submit click method. How can I do this?
namespace ShotgunApp
{
public partial class SingleGame : PhoneApplicationPage
{
public static class AmmoCount
{
public static int userAmmo = startVars.startAmmo;
public static int geniusAmmo = startVars.startAmmo;
}
public static class Global
{
public static int lives = 1;
public static string GeniusMove;
public static string UserMove;
}
public SingleGame()
{
InitializeComponent();
GeniusAmmo.Text = "ammo: " + AmmoCount.geniusAmmo;
UserAmmo.Text = "ammo: " + AmmoCount.userAmmo;
}
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + Move() + " and Genius has " + Genius();
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}
else if (((String)submit.Content) == "Continue")
{
uReload.IsEnabled = true;
uFire.IsEnabled = true;
uShield.IsEnabled = true;
OutcomeDesc.Text = "";
Outcome.Text = "";
submit.Content = "Submit";
}
}
public string Move()
{
if (uReload.IsChecked.HasValue && uReload.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + ++AmmoCount.userAmmo;
Global.UserMove = "reloaded";
}
else if (uShield.IsChecked.HasValue && uShield.IsChecked.Value == true)
{
Global.UserMove = "shielded";
}
else if (uFire.IsChecked.HasValue && uFire.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + --AmmoCount.userAmmo;
Global.UserMove = "fired";
}
else
{
submit.Content = "Enter a move!";
}
return Global.UserMove;
}
public string Genius()
{
GeniusSpeak.Text = "Genius has moved";
submit.Content = "Go!";
Random RandomNumber = new Random();
int x = RandomNumber.Next(0, 3);
if (x == 0)
{
Global.GeniusMove = "reloaded";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
else if (x == 1)
{
Global.GeniusMove = "shielded";
}
else if (x == 2)
{
Global.GeniusMove = "fired";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
return Global.GeniusMove;
}
}
}

Store the last results in data members:
private string lastMoveResult = string.Empty;
private string lastGeniusResult = string.Empty;
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
lastMoveResult = Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
lastGeniusResult = Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + lastMoveResult + " and Genius has " + lastGeniusResult ;
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}

Related

Unity console not showing Debug upon pressing play

I am creating a small login page example and upon pressing play I am not getting any of the Debug messages I am expected if the email/password/confirm password is not according to the conditions set.
Here is the whole code:
Packages
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
using System.Text.RegularExpressions;
Class definition
public class Register : MonoBehaviour
{
public GameObject username;
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Username;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","O","N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-" };
Initiation and setting conditions for username, email, password and confirm password.
// Start is called before the first frame update
void Start()
{
}
public void RegisterButton()
{
print("Registration Successful");
bool UN = false;
bool EM = false;
bool PW = false;
bool CPW = false;
if (Username != "")
{
if (!System.IO.File.Exists(#"E:/UnityTestFolder/" + Username + ".txt"))
{
UN = true;
}
else
{
Debug.LogWarning("Username Taken");
}
}
else
{
Debug.LogWarning("Username field empty");
}
if (Email != "")
{
EmailValidation();
if (EmailValid)
{
if (Email.Contains("#"))
{
if (Email.Contains("."))
{
EM = true;
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email field empty ");
}
if (Password != "")
{
if (Password.Length > 5)
{
PW = true;
}
else
{
Debug.LogWarning("Pass must be at least 6 characters long!");
}
}
else
{
Debug.LogWarning("Password field empty");
}
if (ConfPassword != "")
{
if (ConfPassword == Password)
{
CPW = true;
}
else
{
Debug.LogWarning("Passwords do not match!");
}
}
else
{
Debug.LogWarning("Confirm password field empty");
}
if (UN == true &&EM == true &&PW == true &&CPW == true)
{
bool Clear = true;
int i = 1;
foreach (char c in Password)
{
if (Clear)
{
Password = "";
Clear = false;
}
i++;
char Encrypted = (char)(c * i);
Password += Encrypted.ToString();
}
form = (Username + "\n" + Email + "\n" + Password);
System.IO.File.WriteAllText(#"E:/ UnityTestFolder / " + Username + ".txt", form);
username.GetComponent<InputField>().text = "";
email.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
confPassword.GetComponent<InputField>().text = "";
print("Registration complete");
}
}
Calling update - pressing tab button to navigate between the various placeholders.
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (username.GetComponent<InputField>().isFocused)
{
email.GetComponent<InputField>().Select();
}
if (email.GetComponent<InputField>().isFocused)
{
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused)
{
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != "")
{
RegisterButton();
}
}
Username = username.GetComponent<InputField>().text;
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation()
{
bool SW = false;
bool EW = false;
for (int i = 0; i < Characters.Length; i++)
{
if (Email.StartsWith(Characters[i]))
{
SW = true;
}
}
for (int i = 0; i < Characters.Length; i++)
{
if (Email.EndsWith(Characters[i]))
{
EW = true;
}
}
if (SW = true &&EW == true)
{
EmailValid = true;
}
else
{
EmailValid = false;
}
}
}
Thanks for the help.
Add [ExecuteInEditMode] attribute here:
[ExecuteInEditMode]
public class Register : MonoBehaviour
I have resolved it, it was a stupid mistake, I just had the wrong GameObject in the "On Click" component.
Thanks for all help again.

Xamarin View Not Refreshing

I am having some problems with my Xamarin XAML page and its viewmodel.
I have written the code with a bunch of methods which are executed via commands from the XAML.
Functionally its all working as desired. However, the view is not refreshing when the methods have finished executing. So despite inserting things and removing things from my observable collections (via an API call update), and having a notifypropertychanged event, the page doesn't reload.
Any ideas?
ViewModel (Some properties omitted to fit the character limit for a post)
namespace TechsportiseApp.ViewModels
{
public class ResultsProcessViewModel : INotifyPropertyChanged
{
public ICommand AddTimingCommand { get; set; }
public ICommand AddScanCommand { get; set; }
public ICommand DeleteTimingCommand { get; set; }
public ICommand DeleteScanCommand { get; set; }
public ICommand PublishCommand { get; set; }
public ICommand LoadResultsCommand { get; set; }
public ICommand MissingFinisherCommand { get; set; }
public ICommand MissingTimingCommand { get; set; }
public int RaceId { get; set; }
public DateTime RaceDate { get; set; }
//public ResultsViewModel(Race race)
public ResultsProcessViewModel(Race race)
{
AddTimingCommand = new Command(AddTiming);
AddScanCommand = new Command(AddScan);
DeleteTimingCommand = new Command<int>(DeleteTiming);
DeleteScanCommand = new Command<int>(DeleteScan);
PublishCommand = new Command<string>(Publish);
LoadResultsCommand = new Command<int>(LoadResults);
MissingFinisherCommand = new Command(MissingFinisher);
MissingTimingCommand = new Command(MissingTiming);
Invalid = false;
AddTimingVisibility = false;
AddScanVisibility = false;
AddVisibility = true;
PublishProvisionalVisibility = false;
PublishFinalVisibility = false;
IsBusy = false;
RaceId = race.Id;
RaceDate = race.RaceDate;
RaceStartTime = Convert.ToDateTime(race.RaceStartTime);
Scans = ScansAPI.GetScans(RaceId);
Timings = TimingsAPI.GetTimings(RaceId);
Entries = EntriesAPI.GetEntries(RaceId);
LoadResults(RaceId);
}
ObservableCollection<Result> _results;
public ObservableCollection<Result> Results
{
get
{
return _results;
}
set
{
if (_results != value)
{
_results = value;
OnPropertyChanged("Results");
}
}
}
ObservableCollection<Scan> _scans;
public ObservableCollection<Scan> Scans
{
get
{
return _scans;
}
set
{
if (_scans != value)
{
_scans = value;
OnPropertyChanged("Scans");
}
}
}
ObservableCollection<Timing> _timings;
public ObservableCollection<Timing> Timings
{
get
{
return _timings;
}
set
{
if (_timings != value)
{
_timings = value;
OnPropertyChanged("Timings");
}
}
}
ObservableCollection<RaceEntry> _entries;
public ObservableCollection<RaceEntry> Entries
{
get
{
return _entries;
}
set
{
if (_entries != value)
{
_entries = value;
OnPropertyChanged("Entries");
}
}
}
ObservableCollection<Race> _races;
public ObservableCollection<Race> Races
{
get
{
try
{
var racelist = RacesAPI.GetRaces();
var sortedracelist = new ObservableCollection<Race>(racelist.OrderBy(c => c.Name));
var racecount = racelist.Count();
if (racecount == 0)
{
RaceCountZero = true;
}
else
{
RaceCountZero = false;
}
return racelist;
}
catch
{
Invalid = true;
ValidationError = "Error getting Race List. No internet connection available.";
}
return _races;
}
set
{
if (_races != value)
{
_races = value;
OnPropertyChanged("Races");
}
}
}
string _aboveBelow;
public string AboveBelow
{
get { return _aboveBelow; }
set
{
if (_aboveBelow == value)
return;
_aboveBelow = value;
OnPropertyChanged("AboveBelow");
}
}
string _aboveBelowPosition;
public string AboveBelowPosition
{
get { return _aboveBelowPosition; }
set
{
if (_aboveBelowPosition == value)
return;
_aboveBelowPosition = value;
OnPropertyChanged("AboveBelowPosition");
}
}
string _addHH;
public string AddHH
{
get { return _addHH; }
set
{
if (_addHH == value)
return;
_addHH = value;
OnPropertyChanged("AddHH");
}
}
string _addMM;
public string AddMM
{
get { return _addMM; }
set
{
if (_addMM == value)
return;
_addMM = value;
OnPropertyChanged("AddMM");
}
}
string _addSS;
public string AddSS
{
get { return _addSS; }
set
{
if (_addSS == value)
return;
_addSS = value;
OnPropertyChanged("AddSS");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
void AddTiming()
{
AddScanVisibility = false;
AddTimingVisibility = !AddTimingVisibility;
}
void AddScan()
{
AddScanVisibility = !AddScanVisibility;
AddTimingVisibility = false;
}
void MissingFinisher()
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
var scancount = Scans.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a scan whilst you are offline");
else if (string.IsNullOrEmpty(MissingBib))
throw new Exception("You must enter a bib number");
else if (string.IsNullOrEmpty(AboveBelow))
throw new Exception("You must choose if you are adding the bib above or below");
else if (string.IsNullOrEmpty(AboveBelowPosition))
throw new Exception("You must enter the position you are inserting " + AboveBelow);
else if (Convert.ToInt32(AboveBelowPosition) > scancount)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
else if (Convert.ToInt32(AboveBelowPosition) < 1)
throw new Exception("The position you have chosen to insert above or below does not exist. Please enter a valid value");
//We are good to go
else
{
var InsertedSequence = new int();
var abovebelow = Scans.SingleOrDefault(i => i.Position == Convert.ToInt32(AboveBelowPosition));
var abposition = Convert.ToInt32(AboveBelowPosition);
if (AboveBelow == "Above")
{
InsertedSequence = abovebelow.Sequence + 5;
}
else if (AboveBelow == "Below")
{
InsertedSequence = abovebelow.Sequence - 5;
}
else
{
return;
}
//Need to add resequencing and reallocation of position numbers
var scan = new ScanPost
{
RaceId = RaceId,
BibNumber = MissingBib,
Sequence = InsertedSequence,
Position = abposition,
Reorder = true,
Status = 0
};
var createscan = ScansAPI.CreateScan(scan);
if (createscan.Code != "Created")
throw new Exception("Error creating scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void MissingTiming()
{
Task.Run(() =>
{
try
{
var timingcount = Timings.Count();
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot add a timing whilst you are offline");
//We are good to go
else
{
if (AddHH == "") { AddHH = "0"; }
if (AddMM == "") { AddMM = "0"; }
if (AddSS == "") { AddSS = "0"; }
var ManualEndTime = RaceStartTime.AddHours(Convert.ToDouble(AddHH))
.AddMinutes(Convert.ToDouble(AddMM))
.AddSeconds(Convert.ToDouble(AddSS));
var timing = new TimingPost
{
RaceId = RaceId,
StartTime = RaceStartTime,
EndTime = ManualEndTime,
Reorder = true,
Position = 0,
Status = 0
};
var createtiming = TimingsAPI.CreateTiming(timing);
if (createtiming.Code != "Created")
throw new Exception("Error creating timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Results"));
}
});
}
void DeleteTiming(int timingid)
{
//Do stuff when deleting a timing. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a timing whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(timingid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting timing");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Timings");
Device.BeginInvokeOnMainThread(() => LoadResults(RaceId));
Device.BeginInvokeOnMainThread(() => OnPropertyChanged("Timings"));
}
});
}
void DeleteScan(int scanid)
{
//Do stuff when deleting a scan. It needs to do all this in the observable collection. Then when we submit, we'll update all scans, timings etc with whats in the collection
Task.Run(() =>
{
try
{
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot delete a scan whilst you are offline");
//We are good to go
else
{
var deletetiming = TimingsAPI.DeleteTiming(scanid);
if (deletetiming.Code != "NoContent")
throw new Exception("Error deleting scan");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void Publish(string status)
{
Task.Run(() =>
{
try
{
var publish = new Publish();
publish.RaceId = RaceId;
publish.ResultStatus = status;
Device.BeginInvokeOnMainThread(() => IsBusy = true);
var IsThereConnection = GlobalFunctions.CheckForInternetConnection();
if (IsThereConnection == false)
throw new Exception("You cannot publish results whilst you are offline");
//We are good to go
else
{
var publishrace = RacesAPI.PublishRace(publish);
if (publishrace.Code != "NoContent")
throw new Exception("Error publishing race");
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
ValidationError = ex.Message;
Invalid = true;
});
return;
}
finally
{
Device.BeginInvokeOnMainThread(() => IsBusy = false);
LoadResults(RaceId);
OnPropertyChanged("Results");
}
});
}
void LoadResults(int raceid)
{
var results = new ObservableCollection<Result>();
//Start with the timings
foreach (Timing timing in Timings)
{
var result = new Result();
//Basic details
result.RaceId = RaceId;
result.RaceDate = RaceDate;
result.Status = "Processing";
//Timing Data
result.TimingId = timing.Id;
result.TimingPosition = timing.Position;
result.TimingStatus = timing.Status;
result.StartTime = timing.StartTime;
result.EndTime = timing.EndTime;
var elapsed = result.EndTime - result.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis;
if (elapsed.Milliseconds.ToString().Length > 2)
{
elapsedmillis = elapsed.Milliseconds.ToString().Substring(0, 2);
}
else
{
elapsedmillis = elapsed.Milliseconds.ToString();
}
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if((elapsedhours == "00"))
{
result.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
result.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(result);
}
//Add in the scans
foreach (Result result1 in results)
{
var scan = Scans.FirstOrDefault(p => p.Position == result1.TimingPosition);
if (scan != null)
{
result1.ScanId = scan.Id;
result1.ScanPosition = scan.Position;
result1.ScanStatus = scan.Status;
result1.ScanBibNumber = scan.BibNumber;
}
else
{
result1.ScanId = 0;
result1.ScanPosition = 0;
result1.ScanStatus = 99;
result1.ScanBibNumber = "UNKNOWN";
}
}
//Add any scans which there are no times for (Higher than count)
var timingscount = Timings.Count();
var notimescans = new ObservableCollection<Scan>();
foreach (Scan scan in Scans)
{
if (scan.Position > timingscount)
{
var newresult = new Result();
newresult.RaceId = RaceId;
newresult.RaceDate = RaceDate;
newresult.Status = "Processing";
newresult.ScanId = scan.Id;
newresult.ScanPosition = scan.Position;
newresult.ScanStatus = scan.Status;
newresult.ScanBibNumber = scan.BibNumber;
newresult.TimingId = 0;
newresult.TimingPosition = 99999;
newresult.TimingStatus = 99;
newresult.StartTime = RaceStartTime;
newresult.EndTime = RaceStartTime;
var elapsed = newresult.EndTime - newresult.StartTime;
string elapsedhours = elapsed.Hours.ToString();
string elapsedminutes = elapsed.Minutes.ToString();
string elapsedseconds = elapsed.Seconds.ToString();
string elapsedmillis = elapsed.Milliseconds.ToString();
if (elapsedhours.Length == 1) { elapsedhours = "0" + elapsedhours; }
if (elapsedminutes.Length == 1) { elapsedminutes = "0" + elapsedminutes; }
if (elapsedseconds.Length == 1) { elapsedseconds = "0" + elapsedseconds; }
if (elapsedmillis.Length == 1) { elapsedmillis = "0" + elapsedmillis; }
if ((elapsedhours == "00"))
{
newresult.Elapsed = elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
else
{
newresult.Elapsed = elapsedhours + ":" + elapsedminutes + ":" + elapsedseconds + "." + elapsedmillis;
}
results.Add(newresult);
}
}
//Then add in the entries
foreach (Result result2 in results)
{
var entry = Entries.FirstOrDefault(p => p.BibNumber == result2.ScanBibNumber);
if (entry != null)
{
result2.EntryId = entry.Id;
result2.FirstName = entry.FirstName;
result2.LastName = entry.LastName;
result2.FormattedName = entry.FirstName + " " + entry.LastName.ToUpper();
result2.Gender = entry.Gender;
result2.DateOfBirth = entry.DateOfBirth;
result2.Club = entry.Club;
result2.Team = entry.Team;
result2.EntryBibNumber = entry.BibNumber;
}
else
{
result2.EntryId = 0;
result2.FirstName = "Unknown";
result2.LastName = "ATHLETE";
result2.Gender = "Unknown";
result2.DateOfBirth = DateTime.Now;
result2.Club = "";
result2.Team = "";
result2.EntryBibNumber = "Unknown";
}
}
var sortedresults = new ObservableCollection<Result>(results.OrderBy(c => c.TimingPosition));
Results = sortedresults;
OnPropertyChanged("Results");
}
}
}

Kruskal's Maze Algorithm - Only Working up to dimension 11x11

I am using https://courses.cs.washington.edu/courses/cse326/07su/prj2/kruskal.html psuedocode as reference when writing my code.
Code is in C#, and my code can only generate mazes up to 11x11, anything more than than it will run, seemingly, forever (e.g. 12x11 or 12x12 won't work)
Grid Properties are just storing the dimension of the size of the maze
public class GridProperties
{
private int xLength;
private int yLength;
public GridProperties(int xlength, int ylength)
{
xLength = xlength;
yLength = ylength;
}
public int getXLength()
{
return this.xLength;
}
public int getYLength()
{
return this.yLength;
}
}
Cell Properties generates the grid
public class CellProperties
{
private GridProperties Grid;
private bool topWall, bottomWall, rightWall, leftWall;
private int? xCoord, yCoord;
private CellProperties topCell, bottomCell, rightCell, leftCell;
private CellProperties topParentCell, bottomParentCell, rightParentCell, leftParentCell;
private HashSet<String> passageID = new HashSet<String>();
public CellProperties(GridProperties grid = null, int? targetXCoord = null, int? targetYCoord = null,
CellProperties tpCell = null, CellProperties bpCell = null,
CellProperties rpCell = null, CellProperties lpCell = null)
{
this.Grid = grid;
this.xCoord = targetXCoord;
this.yCoord = targetYCoord;
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
this.topWall = true;
this.bottomWall = true;
this.rightWall = true;
this.leftWall = true;
this.topParentCell = tpCell;
this.bottomParentCell = bpCell;
this.rightParentCell = rpCell;
this.leftParentCell = lpCell;
this.topCell = this.setTopCell();
this.bottomCell = this.setBottomCell();
if (this.yCoord == 0)
{
this.rightCell = this.setRightCell();
}
this.leftCell = this.setLeftCell();
}
public CellProperties setTopCell()
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == this.Grid.getYLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord, this.yCoord + 1, null, this, null, null);
}
}
public CellProperties setBottomCell()
{
if (this.yCoord == 0)
{
return new CellProperties();
}
else
{
return this.bottomParentCell;
}
}
public CellProperties setRightCell()
{
if (this.Grid == null)
{
return null;
}
if (this.xCoord == this.Grid.getXLength() - 1)
{
return new CellProperties();
}
else
{
return new CellProperties(this.Grid, this.xCoord + 1, this.yCoord, null, null, null, this);
}
}
public CellProperties setLeftCell( )
{
if (this.xCoord == 0)
{
return new CellProperties();
}
else
{
if (this.Grid == null)
{
return null;
}
if (this.yCoord == 0)
{
return this.leftParentCell;
}
else
{
CellProperties buffer = this.bottomCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.bottomParentCell;
}
buffer = buffer.leftParentCell.topCell;
for (int depth = 0; depth < this.yCoord - 1; depth++)
{
buffer = buffer.topCell;
}
buffer.rightCell = this;
return buffer;
}
}
}
public GridProperties getGrid()
{
return this.Grid;
}
public CellProperties getBottomCell()
{
return this.bottomCell;
}
public CellProperties getTopCell()
{
return this.topCell;
}
public CellProperties getLeftCell()
{
return this.leftCell;
}
public CellProperties getRightCell()
{
return this.rightCell;
}
public void setBottomWall(Boolean newBottomWall)
{
this.bottomWall = newBottomWall;
}
public void setTopWall(Boolean newTopWall)
{
this.topWall = newTopWall;
}
public void setLeftWall(Boolean newLeftWall)
{
this.leftWall = newLeftWall;
}
public void setRightWall(Boolean newRightWall)
{
this.rightWall = newRightWall;
}
public Boolean getBottomWall()
{
return this.bottomWall;
}
public Boolean getTopWall()
{
return this.topWall;
}
public Boolean getLeftWall()
{
return this.leftWall;
}
public Boolean getRightWall()
{
return this.rightWall;
}
public void updatePassageID(String newPassageID)
{
this.passageID.Add(newPassageID);
}
public void setPassageID(HashSet<String> newPassageID)
{
this.passageID = new HashSet<string>(newPassageID);
}
public HashSet<String> getPassageID()
{
return this.passageID;
}
}
This class is where the magic happens ... or suppose to happen.
public class KruskalMazeGenerator
{
private CellProperties Cell0x0;
private CellProperties CurrentCell;
private CellProperties NeighbourCell;
private int WallsDown;
private int TotalNumberOfCells;
private Random rnd = new Random();
private int rndXCoord, rndYCoord;
private String rndSide;
public KruskalMazeGenerator(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
WallsDown = 0;
TotalNumberOfCells = Cell0x0.getGrid().getXLength() * Cell0x0.getGrid().getYLength();
}
public void selectRandomCellCoords()
{
this.rndXCoord = rnd.Next(0, this.Cell0x0.getGrid().getXLength());
this.rndYCoord = rnd.Next(0, this.Cell0x0.getGrid().getYLength());
}
public void selectRandomSide(String[] possibleSides)
{
if (possibleSides.Length != 0)
{
this.rndSide = possibleSides[rnd.Next(0, possibleSides.Length)];
}
}
public void selectRandomCurrentCell()
{
this.selectRandomCellCoords();
this.CurrentCell = this.Cell0x0;
for (int xWalk = 0; xWalk < this.rndXCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getRightCell();
}
for (int xWalk = 0; xWalk < this.rndYCoord; xWalk++)
{
this.CurrentCell = this.CurrentCell.getTopCell();
}
}
public CellProperties checkWallBetweenCurrentAndNeighbour(List<String> possibleSides)
{
if (this.rndSide == "top")
{
if (this.CurrentCell.getTopCell() == null || this.CurrentCell.getTopCell().getGrid() == null)
{
possibleSides.Remove("top");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getTopCell();
}
else if (this.rndSide == "bottom")
{
if (this.CurrentCell.getBottomCell() == null || this.CurrentCell.getBottomCell().getGrid() == null)
{
possibleSides.Remove("bottom");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getBottomCell();
}
else if (this.rndSide == "left")
{
if (this.CurrentCell.getLeftCell() == null || this.CurrentCell.getLeftCell().getGrid() == null)
{
possibleSides.Remove("left");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getLeftCell();
}
else if (this.rndSide == "right")
{
if (this.CurrentCell.getRightCell() == null || this.CurrentCell.getRightCell().getGrid() == null)
{
possibleSides.Remove("right");
this.selectRandomSide(possibleSides.ToArray());
return this.checkWallBetweenCurrentAndNeighbour(possibleSides);
}
return this.CurrentCell.getRightCell();
}
return null;
}
public void selectRandomNeigbhourCell()
{
this.selectRandomSide(new String[4] { "top", "bottom", "left", "right" });
this.NeighbourCell = this.checkWallBetweenCurrentAndNeighbour(new List<String>(new String[4] { "top", "bottom", "left", "right" }));
}
public void checkForDifferentPassageID()
{
if (!this.CurrentCell.getPassageID().SetEquals(this.NeighbourCell.getPassageID()))
{
if (this.rndSide == "top")
{
this.CurrentCell.setTopWall(false);
this.NeighbourCell.setBottomWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "bottom")
{
this.CurrentCell.setBottomWall(false);
this.NeighbourCell.setTopWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "left")
{
this.CurrentCell.setLeftWall(false);
this.NeighbourCell.setRightWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
else if (this.rndSide == "right")
{
this.CurrentCell.setRightWall(false);
this.NeighbourCell.setLeftWall(false);
this.unionAndResetPassageID();
this.WallsDown += 1;
}
}
}
public void unionAndResetPassageID()
{
HashSet<String> oldCurrentPassageID = new HashSet<String>(this.CurrentCell.getPassageID());
HashSet<String> oldNeighbourPassageID = new HashSet<String>(this.NeighbourCell.getPassageID());
HashSet <String> newPassageID = new HashSet<String>();
newPassageID = this.CurrentCell.getPassageID();
newPassageID.UnionWith(this.NeighbourCell.getPassageID());
CellProperties xwalkCell = new CellProperties();
CellProperties ywalkCell = new CellProperties();
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
xwalkCell = xWalk == 0 ? this.Cell0x0 : xwalkCell.getRightCell();
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
xwalkCell.setBottomWall(xWalk == 0 && yWalk == 0 ? false : xwalkCell.getBottomWall());
xwalkCell.setBottomWall(xWalk == this.Cell0x0.getGrid().getXLength() - 1 && yWalk == this.Cell0x0.getGrid().getYLength() - 1 ? false : xwalkCell.getBottomWall());
ywalkCell = yWalk == 0 ? xwalkCell : ywalkCell.getTopCell();
if (ywalkCell.getPassageID().SetEquals(oldCurrentPassageID) ||
ywalkCell.getPassageID().SetEquals(oldNeighbourPassageID))
{
ywalkCell.setPassageID(newPassageID);
}
}
}
}
public CellProperties createMaze()
{
while (this.WallsDown < this.TotalNumberOfCells - 1)
{
this.selectRandomCurrentCell();
this.selectRandomNeigbhourCell();
if (this.NeighbourCell != null)
{
this.checkForDifferentPassageID();
}
}
return this.Cell0x0;
}
}
then this is my visual representation class
public class drawGrid : CellProperties
{
private CellProperties Cell0x0 = new CellProperties();
private CellProperties yWalkBuffer = new CellProperties();
private CellProperties xWalkBuffer = new CellProperties();
private String bottomWall = "";
private String topWall = "";
private String leftAndrightWalls = "";
public drawGrid(CellProperties cell0x0)
{
Cell0x0 = cell0x0;
}
private void WallDrawingReset()
{
this.bottomWall = "\n";
this.topWall = "\n";
this.leftAndrightWalls = "\n";
}
private void Draw()
{
// draw bottom wall
{
if (this.bottomWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.bottomWall);
}
}
Console.Write(this.leftAndrightWalls);
// draw top wall
{
if (topWall == "\n")
{
Console.Write("");
}
else
{
Console.Write(this.topWall);
}
}
}
public void yWalk()
{
for (int yWalk = 0; yWalk < this.Cell0x0.getGrid().getYLength(); yWalk++)
{
this.yWalkBuffer = yWalk == 0 ? this.Cell0x0 : this.yWalkBuffer.getTopCell();
this.WallDrawingReset();
this.xWalk(yWalk);
this.Draw();
}
}
private void xWalk(int yWalk)
{
for (int xWalk = 0; xWalk < this.Cell0x0.getGrid().getXLength(); xWalk++)
{
this.xWalkBuffer = xWalk == 0 ? this.yWalkBuffer : this.xWalkBuffer.getRightCell();
if (yWalk == 0)
{
this.bottomWall = xWalkBuffer.getBottomWall() ? this.bottomWall + "----" : this.bottomWall + " ";
this.topWall = xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
else
{
this.topWall = this.xWalkBuffer.getTopWall() ? this.topWall + "----" : this.topWall + " ";
}
if (xWalk == 0)
{
leftAndrightWalls = this.xWalkBuffer.getLeftWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
else
{
leftAndrightWalls = this.xWalkBuffer.getRightWall() ? this.leftAndrightWalls + "| " : this.leftAndrightWalls + " ";
}
}
}
}
this is how i call them
class Program
{
static void Main(string[] args)
{
{
CellProperties cell = new CellProperties(new GridProperties(12, 11), 0, 0, null, null, null, null);
drawGrid draw = new drawGrid(cell);
draw.yWalk();
KruskalMazeGenerator kmaze = new KruskalMazeGenerator(cell);
cell = kmaze.createMaze();
Console.WriteLine("Final");
draw = new drawGrid(cell);
draw.yWalk();
}
Console.ReadKey();
}
}
Since I got you guys here, please don't mind pitching in what I can improve on as in coding style and other things that you are displeased with.
Thanks in advance.
Error seems to be here:
this.updatePassageID(this.xCoord.ToString() + this.yCoord.ToString());
Image those two scenarios:
xCoord = 1 and yCoord = 11.
xCoord = 11 and yCoord = 1.
both those result in newPassageID of 111.
So simply change the line to
this.updatePassageID(this.xCoord.ToString() + "|" + this.yCoord.ToString());
or written more sexy:
this.updatePassageID($"{xCoord}|{yCoord}");
With this you will receive
1|11 for the first scenario and 11|1 for the second which differs.
Edit based on comments:
I saw that your code is looping endlessly in the method createMaze. This method calls a method called checkForDifferentPassageID in there you check if two collections are equal or not. Once I saw that those collections are of type HashSet<string>, I thought that maybe your strings you put into the HashSet arent as unique as you think they are and there we go. So overall it took me like 10 minutes.

why is MrSystem.Windows.Forms.TextBox, Text: dsadasd keep apearring?

case 2:
if (jk.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Mr" + name;
}
else
{
result = "Mr" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Mrs" + name;
}
else
{
result = "Ms" + name;
}
}
txbx1.Text = result;
break;
this is the code i use here, but
whenever click the button this keep appearing
System.Windows.Forms.TextBox, Text: dsndaslkdna.
i have try change it with txbx1 without .Text but i only become error can any one help with this?
private void button1_Click(object sender, EventArgs e)
{
string result;
//combobox : lg,Sex,stat
//textbox : name,show
//button : button1
switch (lg.SelectedIndex)
{
case 0:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Bapak" + name;
}
else
{
result = "Mas" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Ibu" + name;
}
else
{
result = "Mbak" + name;
}
}
show.Text = result;
break;
case 1:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Xiansheng" + name;
}
else
{
result = "Xiansheng" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Taitai" + name;
}
else
{
result = "Xiaojie" + name;
}
}
show.Text = result;
break;
case 2:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Mr" + name;
}
else
{
result = "Mr" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Mrs" + name;
}
else
{
result = "Ms" + name;
}
}
show.Text = result;
break;
case 3:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "San" + name;
}
else
{
result = "Kun" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "San" + name;
}
else
{
result = "Chan" + name;
}
}
show.Text = result;
break;
case 4:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Ssi" + name;
}
else
{
result = "Hyung" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Ssi" + name;
}
else
{
result = "Noona" + name;
}
}
show.Text = result;
break;
case 5:
if (Sex.SelectedIndex == 0)
{
if (stat.SelectedIndex == 0)
{
result = "Monsieur" + name;
}
else
{
result = "Monsieur" + name;
}
}
else
{
if (stat.SelectedIndex == 0)
{
result = "Madame" + name;
}
else
{
result = "Mademoiselle" + name;
}
}
show.Text = result;
break;
}
here the full one

Selecting and displaying certain items from list based on specific property

i have a list of objects saved in a text file that I can display onto a form. However now I need a button that will only display certain objects from the list based on a property, in my case brand. Below is the code I've been trying to use but cant get it to work.
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
Underneath is the full code, in case more information is needed, thanks for your help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Car_Manager
{
public partial class Form1 : Form
{
string currentfile;
Car c;
int curIndex = -1;
List<Car> cars = new List<Car>();
public Form1()
{
InitializeComponent();
c = new Car();
saveFileDialog1.CreatePrompt = true;
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "myText";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*";
}
public void clearForm()
{
txtBrand.Text = "";
txtModel.Text = "";
txtYear.Text = "";
txtPrice.Text = "";
txtNumMiles.Text = "";
txtInformation.Text = "";
radAutomatic.Checked = false;
radManual.Checked = false;
radConvertible.Checked = false;
radCoupe.Checked = false;
radEstate.Checked = false;
radHatchback.Checked = false;
radHPV.Checked = false;
radSaloon.Checked = false;
radSUV.Checked = false;
}
private void DisplayCar()
{
txtBrand.Text = c.Brand;
txtModel.Text = c.Model;
txtYear.Text = c.Year;
txtPrice.Text = c.Price;
txtNumMiles.Text = c.NumMiles;
DisplayBody();
DisplayGear();
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void FormToObject()
{
c.Brand = txtBrand.Text;
c.Model = txtModel.Text;
c.Year = txtYear.Text;
c.Price = txtPrice.Text;
c.NumMiles = txtNumMiles.Text;
BodyCheck();
GearCheck();
}
private void BodyCheck()
{
if (radHatchback.Checked == true)
{ c.Body = radHatchback.Text; }
else if (radHPV.Checked == true)
{ c.Body = radHPV.Text; }
else if (radSUV.Checked == true)
{ c.Body = radSUV.Text; }
else if (radSaloon.Checked == true)
{ c.Body = radSaloon.Text; }
else if (radConvertible.Checked == true)
{ c.Body = radConvertible.Text; }
else if (radCoupe.Checked == true)
{ c.Body = radCoupe.Text; }
else if (radEstate.Checked == true)
{ c.Body = radEstate.Text; }
}
private void DisplayBody()
{
if (c.Body == "Hatchback")
{ radHatchback.PerformClick(); }
else if (c.Body == "HPV")
{ radHPV.PerformClick(); }
else if (c.Body == "SUV")
{ radSUV.PerformClick(); }
else if (c.Body == "Convertible")
{ radConvertible.PerformClick(); }
else if (c.Body == "Saloon")
{ radSaloon.PerformClick(); }
else if (c.Body == "Coupe")
{ radSaloon.PerformClick(); }
else if (c.Body == "Estate")
{ radEstate.PerformClick(); }
}
private void GearCheck()
{
if (radAutomatic.Checked == true)
{ c.GearBox = radAutomatic.Text; }
else if (radManual.Checked == true)
{ c.GearBox = radManual.Text; }
}
private void DisplayGear()
{
if (c.GearBox == "Manual")
{ radManual.PerformClick(); }
else if (c.GearBox == "Automatic")
{ radAutomatic.PerformClick(); }
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
currentfile = openFileDialog1.FileName;
saveToolStripMenuItem.Enabled = true;
Stream s1 = openFileDialog1.OpenFile();
StreamReader reader = new StreamReader(s1);
while (reader.Peek() != -1)
{
string str = reader.ReadLine();
Car c = new Car();
c.ReadString(str);
cars.Add(c);
}
curIndex = 0;
c = cars[curIndex];
DisplayCar();
reader.Close();
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save everything in a dialog box
saveFileDialog1.ShowDialog();
// Open the file and save the information
Stream textOut = saveFileDialog1.OpenFile();
StreamWriter writer = new StreamWriter(textOut);
FormToObject();
string str = c.GetToString();
writer.WriteLine(str);
writer.Close();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
// Save the file with the current file name
FileStream f1 = new FileStream(currentfile, FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(f1);
// get the object into a string
FormToObject();
StreamWriter file = new System.IO.StreamWriter(f1);
cars.ForEach(file.WriteLine);
file.Close();
}
private void btnAddInfo_Click(object sender, EventArgs e)
{
c.Information.Add(txtAddInfo.Text);
string str = "";
for (int i = 0; i < c.Information.Count(); i++)
str += c.Information[i] + "\r\n";
txtInformation.Text = str;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtInformation.Text = "";
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void btnPreviousCar_Click(object sender, EventArgs e)
{
curIndex--;
if (curIndex < 0)
curIndex = cars.Count - 1;
c = cars[curIndex];
DisplayCar();
}
private void btnNextCar_Click(object sender, EventArgs e)
{
curIndex++;
if (curIndex >= cars.Count)
curIndex = 0;
c = cars[curIndex];
DisplayCar();
}
private void button1_Click(object sender, EventArgs e)
{
int a = cars.Count;
textBox1.Text = Convert.ToString(cars[2]);
}
private void btnEditCar_Click(object sender, EventArgs e)
{
txtBrand.ReadOnly = false;
txtModel.ReadOnly = false;
txtYear.ReadOnly = false;
txtPrice.ReadOnly = false;
txtNumMiles.ReadOnly = false;
txtAddInfo.ReadOnly = false;
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Car> BrandSelect = new List<Car>(cars);
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
DisplayCar();
}
private void yearToolStripMenuItem1_Click(object sender, EventArgs e)
{
}
}
class Car
{
//List of properties
private string brand;
private string model;
private string year;
private string price;
private string numMiles;
private string body;
private string gearbox;
private List<string> information;
//Constructor
public Car() //Default Constructor
{
brand = "Unknown";
model = "Unknown";
year = "Unknown";
price = "Unknown";
numMiles = "Unknown";
information = new List<string>();
}
public Car(string str)
{
information = new List<string>();
ReadString(str);
}
public void ReadString(string str)
{
string[] words = str.Split('|');
int Nwords = words.Count();
brand = words[0];
model = words[1];
year = words[2];
price = words[3];
numMiles = words[4];
body = words[5];
gearbox = words[6];
information.Clear();
for (int i = 7; i < Nwords; i++)
information.Add(words[i]);
}
//Methods
public string Brand
{
get { return brand; }
set { brand = value; }
}
public string Model
{
get { return model; }
set { model = value; }
}
public string Year
{
get { return year; }
set { year = value; }
}
public string Price
{
get { return price; }
set { price = value; }
}
public string NumMiles
{
get { return numMiles; }
set { numMiles = value; }
}
public string Body
{
get { return body; }
set { body = value; }
}
public string GearBox
{
get { return gearbox; }
set { gearbox = value; }
}
public List<string> Information
{
get { return information; }
set { information = value; }
}
public string GetToString()
{
string str = "";
str += brand + "|";
str += model + "|";
str += year + "|";
str += price + "|";
str += numMiles + "|";
str += body + "|";
str += gearbox + "|";
for (int i = 0; i < information.Count(); i++)
str += information[i] + "|";
return str;
}
}
}
First thing that I noticed:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
// You already have list of cars, this line will copy your list
// into a new one, which is unnecessary work (you don't use it later).
// You don't need this:
List<Car> BrandSelect = new List<Car>(cars);
// the "c" here is not the "c" that is the field of your form
// it's a part of the syntax of linq query
var SelectBrand = from c in BrandSelect
where c.Brand == textBox1.Text
select c;
// This method displays what is in the field "c" (this.c)
// ... and the content of "c" didn't change at all
DisplayCar();
}
the code here should be, for example:
private void brandToolStripMenuItem_Click(object sender, EventArgs e)
{
//beware this can be null
this.c = (from a in this.cars
where a.Brand == textBox1.Text
select a).FirstOrDefault();
}
[msdn] introduction to linq queries

Categories