Can I add values to an instance of an object after I have used the constructor?
For instance I have this code. I have to make a list of objects which require a number n, and the time (which are recieved as arguments). The problem is that the time can be anywhere so I can't use it in a constructor.
public List<IAction> Dispatch(string[] arg)
{
int time;
int i = 0;
int j = 0;
List<IAction> t = new List<IAction>(10);
do
{
if (int.Parse(arg[j]) >= 0 && int.Parse(arg[j]) <= 20)
{
t.Add(new ComputeParam(int.Parse(arg[j])));
i++;
j++;
}
else
{
if (arg[i][0] == '/' && arg[i][1] == 't')
{
Options opt = new Options();
j++;
time=opt.Option(arg[i]); //sets the time 0,1000 or 2000
}
}
} while (i != arg.Length);
return t;
}
After finishing making the list can I do something like:
for(int i=0; i<=t.Count; i++)
{
*add time to t[i]*
}
How do I do this?
Thanks in advance!
Edit :
here is the ComputeParam class
public class ComputeParam : IAction
{
int n;
int time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this.n = n;
}
public void run()
{
Factorial Fact = new Factorial();
Fact.Progression += new Factorial.ProgressEventHandler(Progress);
Console.WriteLine(" ");
Console.Write("\n" + "Partial results : ");
Console.CursorLeft = 35;
Console.Write("Progress : ");
int Result = Fact.CalculateFactorial(n, time);
Console.WriteLine(" ");
Console.WriteLine("The factorial of " + n + " is : " + Result);
Console.WriteLine("Press Enter to continue...");
Console.CursorTop -= 2;
Console.CursorLeft = 0;
Console.ReadLine();
}
public void Progress(ProgressEventArgs e)
{
int result = e.getPartialResult;
int stack_value = e.getValue;
double max = System.Convert.ToDouble(n);
System.Convert.ToDouble(stack_value);
double percent = (stack_value / max) * 100;
Console.CursorLeft = 18;
Console.Write(result + " ");
Console.CursorLeft = 46;
Console.Write(System.Convert.ToInt32(percent) + "% ");
}
}
If the object has a public property, I don't see why not.
Edit: Looks like you need to add a public property to your class. Also note, given that there is a public constructor that takes 0 params, you should also add a property for n.
public class ComputeParam : IAction
{
int _n;
int _time;
public ComputeParam()
{
}
public ComputeParam(int n)
{
this._n = n;
}
public int Time
{
get { return this._time; }
set { this._time = value; }
}
public int N
{
get { return this._n; }
set { this._n = value; }
}
for(int i = 0; i < t.Count; i++)
{
((ComputeParam)t[i]).Time = 6;
}
Related
Max open trades
Hi, guys.. I have to modify a bot to set a maximum trades of whatever number I give it.
At the moment it opens max one trade but I want to be able to tell the bot to have 3 open trades at the same time, for example...
Is there a way to do it?
CODE BELOW!
using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.Indicators;
namespace cAlgo.Robots
{
[Robot(AccessRights = AccessRights.None)]
public class ThreeBarInsideBar : Robot
{
int upClose;
int upCloseBefore;
int insideBar;
int downClose;
int downCloseBefore;
int counter =0;
Position position;
[Parameter(DefaultValue = 10000)]
public int Volume { get; set; }
[Parameter("Stop Loss (pips)", DefaultValue = 10)]
public int StopLoss { get; set; }
[Parameter("Take Profit (pips)", DefaultValue = 10)]
public int TakeProfit { get; set; }
protected override void OnBar()
{
if(Trade.IsExecuting){
return;
}
if(MarketSeries.Close[MarketSeries.Close.Count-1] > MarketSeries.Close[MarketSeries.High.Count-2]){
upClose = 1;
}else{
upClose = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-3] > MarketSeries.Close[MarketSeries.Close.Count-4]){
upCloseBefore = 1;
}else{
upCloseBefore = 0;
}
if((MarketSeries.High[MarketSeries.Close.Count-2] < MarketSeries.High[MarketSeries.Close.Count-3])
&&(MarketSeries.Low[MarketSeries.Close.Count-2]> MarketSeries.Low[MarketSeries.Close.Count-3])){
insideBar = 1;
}else{
insideBar = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-1] < MarketSeries.Close[MarketSeries.Low.Count-2]){
downClose = 1;
}else{
downClose = 0;
}
if(MarketSeries.Close[MarketSeries.Close.Count-3] < MarketSeries.Close[MarketSeries.Close.Count-4]){
downCloseBefore = 1;
}else{
downCloseBefore = 0;
}
if(counter == 0){
if(upClose == 1 && insideBar == 1 && upCloseBefore == 1){
Trade.CreateMarketOrder(TradeType.Buy,Symbol,Volume);
}
if( downClose == 1 && insideBar == 1 && downCloseBefore == 1){
Trade.CreateMarketOrder(TradeType.Sell,Symbol,Volume);
}
}
}
protected override void OnPositionOpened(Position openedPosition)
{
position = openedPosition;
counter = 1;
Trade.ModifyPosition(openedPosition, GetAbsoluteStopLoss(openedPosition, StopLoss), GetAbsoluteTakeProfit(openedPosition, TakeProfit));
}
protected override void OnPositionClosed(Position position)
{
counter=0;
}
private double GetAbsoluteStopLoss(Position position, int stopLossInPips)
{
return position.TradeType == TradeType.Buy
? position.EntryPrice - Symbol.PipSize * stopLossInPips
: position.EntryPrice + Symbol.PipSize * stopLossInPips;
}
private double GetAbsoluteTakeProfit(Position position, int takeProfitInPips)
{
return position.TradeType == TradeType.Buy
? position.EntryPrice + Symbol.PipSize * takeProfitInPips
: position.EntryPrice - Symbol.PipSize * takeProfitInPips;
}
}
}
Have not tried much since I do not know how to do it!
Type definitions
using System;
public enum Direction { Right, Left, Forward };
class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get { return age; }
}
public int Height
{
get { return height; }
}
public int Cordinates_x
{
get { return cordinates_x; }
set { cordinates_x = value; }
}
public int Cordinates_y
{
get { return cordinates_y; }
set { if (value > 0) cordinates_y = value; }
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
Usage
class Program
{
static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
horse ob = new horse();
ob.Jump(minAge);
ob.move();
ob.Print();
Console.ReadKey();
}
}
I get these errors in Visual Studio:
'Chaharpa' does not contain a constructor that takes 0 arguments
The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)
The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)
In the class Chaharpa you defined two constructors, both take arguments.
Creating your own constructor overrides the default constructor.
Usually, when inheriting from a base class you want to initialize the inheriting class with parameters that are used to initialize the base class, look more at this thread.
The horse class inside Chaharpa and Chaharpaclass are not public.
Changing classes horse and Chaharpa to public and accessing it as:
Chaharpa.horse ob = new Chaharpa.horse();
is the right way to go.
Here are some mitigations to the code:
using System;
using System.ComponentModel;
public enum Direction
{ Right, Left, Forward };
public class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa()
{
}
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get { return age; }
}
public int Height
{
get { return height; }
}
public int Cordinates_x
{
get { return cordinates_x; }
set { cordinates_x = value; }
}
public int Cordinates_y
{
get { return cordinates_y; }
set { if (value > 0) cordinates_y = value; }
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
public class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void move()
{
throw new NotImplementedException();
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
class Program
{
static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
Chaharpa.horse ob = new Chaharpa.horse();
ob.Jump(minAge);
// You can call the Move defined in Chaharpa
ob.Move(<PASS DIRECTION PARAMETER HERE>);
ob.Print();
Console.ReadKey();
}
}
First, you have to study more about object creation in C#. When creating an object of a child class inside the child class constructor, it's calling the base class constructor.
using System;
public class Program
{
public static void Main()
{
Child child = new Child();
}
}
public class Parent{
public Parent(){
Console.WriteLine("I am parent");
}
}
public class Child : Parent {
public Child(){
Console.WriteLine("I am child");
}
}
Output
I am parent
I am child
When you creating a class there is a default constructor (the constructor which takes 0 arguments). But when you create another constructor (which takes more than 0 arguments) default constructor will replaced by that. You have to manually create default constructor. So at the runtime, it's trying to call the default constructor of the base class constructor. But since it's gone this error occurs.
'Chaharpa' does not contain a constructor that takes 0 arguments
Then you have to study about nested classes in C#.
You can't just call inner class by it's name. You have to reference it from the outer class.
using System;
public class Program
{
public static void Main()
{
Outer.Inner child = new Outer.Inner();
}
}
public class Outer{
public Outer(){
Console.WriteLine("I am outer");
}
public class Inner : Outer {
public Inner(){
Console.WriteLine("I am inner");
}
}
}
Output
I am outer
I am inner
That's why you get the error The type or namespace name 'horse' could not be found (are you missing a using directive or an assembly reference?)
This code will work.
using System;
public enum Direction
{ Right, Left,Forward};
class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa(){}
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get{ return age; }
}
public int Height
{
get{ return height;}
}
public int Cordinates_x
{
get{ return cordinates_x;}
set{ cordinates_x = value;}
}
public int Cordinates_y
{
get{return cordinates_y;}
set{ if (value > 0)cordinates_y = value;}
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
public class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
public class Program
{
public static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
Chaharpa.horse ob = new Chaharpa.horse();
ob.Jump(minAge);
ob.Print();
}
}
Use one file for one class is a good practice.
I searched an answer for my question but I could not find anything. I am sorry if there is a similar theme.
So I need to sort a list of objects by their property and I have to use bubble sort. How can I make it without using methods like "list.sort".
Thank you in advance!
using System;
using System.Collections.Generic;
class Animals
{
public int id { get; set; }
public string name { get; set; }
public string color { get; set; }
public int age { get; set; }
}
class Program
{
static void Main()
{
Console.Write("How much animals you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newAnimals = new List<Animals>(count);
Animals animal = new Animals();
newAnimals.Add(animal);
for (int i = 0; i < count; i++)
{
newAnimals[i].id = i;
Console.Write("Write name for animal: " + i + ": ");
newAnimals[i].name = Console.ReadLine();
Console.Write("Write age for animal: " + i + ": ");
newAnimals[i].age = int.Parse(Console.ReadLine());
Console.Write("Write color for animal: " + i + ": ");
newAnimals[i].color = Console.ReadLine();
newAnimals.Add(new Animals() { id = 1, name = "name" });
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
Generic, with dynamic property selector :
public static class MyExtensions
{
public static void BubbleSort<T>(this List<T> list, Func<T, int> selector)
{
while (true)
{
bool changed = false;
for (int i = 1; i < list.Count; i++)
{
if (selector(list[i - 1]) > selector(list[i]))
{
T temp = list[i - 1];
list[i - 1] = list[i];
list[i] = temp;
changed = true;
}
}
if (!changed)
break;
}
}
}
Usage:
unsortedList.BubbleSort(x => x.SortProperty);
here you go (assuming that you want to sort by id)
for (int i = 0; i < newAnimals.Count; i++)
{
for (int j = 1; j <= i; j++)
{
if (newAnimals[j - 1].id > newAnimals[j].id)
{
Animals temp = newAnimals[j - 1];
newAnimals[j - 1] = newAnimals[j];
newAnimals[j] = temp;
}
}
}
I am creating a program that intakes info for the number of visits on separate days to a centre. I am using an array to keep track of that info, but I also need to create a method that calls up the day with the least number of visits and then displays it in an output.
class ScienceCentreVisitation
{
private string centreName;
private string city;
private decimal ticketPrice;
private string[] visitDate;
private int[] adultVisitors;
private decimal[] totalRevenue;
//constructors
public ScienceCentreVisitation()
{
}
public ScienceCentreVisitation(string cent)
{
centreName = cent;
}
public ScienceCentreVisitation(string cent, string cit, decimal price, string[] date, int[] visit, decimal[] rev)
{
visitDate = new string[date.Length];
adultVisitors = new int[visit.Length];
totalRevenue = new decimal[rev.Length];
Array.Copy(date, 0, visitDate, 0, date.Length);
Array.Copy(visit, 0, adultVisitors, 0, adultVisitors.Length);
Array.Copy(rev, 0, totalRevenue, 0, rev.Length);
centreName = cent;
city = cit;
ticketPrice = price;
}
//properties
public string CentreName
{
get
{
return centreName;
}
set
{
centreName = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public decimal TicketPrice
{
get
{
return ticketPrice;
}
set
{
ticketPrice = value;
}
}
public string[] VisitDate
{
get
{
return visitDate;
}
set
{
visitDate = value;
}
}
public int[] AdultVisitors
{
get
{
return adultVisitors;
}
set
{
adultVisitors = value;
}
}
public decimal[] TotalRevenue
{
get
{
return totalRevenue;
}
set
{
totalRevenue = value;
}
}
//methods
public decimal CalculateTotalRevenue()
{
decimal totalRev;
int cntOfValidEntries;
int total = 0;
foreach (int c in adultVisitors)
total += c;
cntOfValidEntries = TestForZeros();
totalRev = (decimal)total / cntOfValidEntries;
return totalRev;
}
public int TestForZeros()
{
int numberOfTrueVisits = 0;
foreach (int cnt in adultVisitors)
if (cnt != 0)
numberOfTrueVisits++;
return numberOfTrueVisits;
}
public int GetIndexOfLeastVisited()
{
int minVisIndex = 0;
for (int i = 1; i < adultVisitors.Length; i++)
if (adultVisitors[i] < adultVisitors[minVisIndex])
minVisIndex = i;
return minVisIndex;
}
public int GetLeastVisited()
{
return adultVisitors[GetIndexOfLeastVisited()];
}
public string GetDateWithLeastVisited()
{
return visitDate[GetIndexOfLeastVisited()];
}
public int GetIndexOfMostRevenue()
{
int maxRevIndex = 0;
for (int i = 1; i < totalRevenue.Length; i++)
if (totalRevenue[i] > totalRevenue[maxRevIndex])
maxRevIndex = i;
return maxRevIndex;
}
public decimal GetMostRevenue()
{
return totalRevenue[GetIndexOfMostRevenue()];
}
public string GetDateWithMostRevenue()
{
return visitDate[GetIndexOfMostRevenue()];
}
public override string ToString()
{
return "Name of Centre: " + centreName +
"\nCity: " + city +
"\n Price of ticket: " + ticketPrice +
"\nDate of Least One-Day Adult Visitors:\t\t" + GetDateWithLeastVisited() +
"\nNumber of Least One-Day Adult Visitors:\t\t" + GetLeastVisited() +
"\nDate of Most Total Revenue Collected:\t\t" + GetDateWithMostRevenue() +
"\nHighest Total Revenue Collected:\t\t" + GetMostRevenue();
}
}
Other class:
class ScienceCentreApp
{
static void Main(string[] args)
{
string centreName;
string city;
decimal ticketPrice = 0;
int visitorCnt;
string[] dArray = new String[5];
int[] adultVisitors = new int[5];
decimal[] totalRevenue = new decimal[5];
char enterMoreData = 'Y';
ScienceCentreVisitation scv;
do
{
visitorCnt = GetData(out centreName, out city, out ticketPrice, dArray, adultVisitors, totalRevenue);
scv = new ScienceCentreVisitation(centreName, city, ticketPrice, dArray, adultVisitors, totalRevenue);
Console.Clear();
Console.WriteLine(scv);
Console.Write("\n\n\n\nDo you want to enter more data - " +
"(Enter y or n)? ");
if (char.TryParse(Console.ReadLine(), out enterMoreData) == false)
Console.WriteLine("Invalid data entered - " +
"No recorded for your respones");
} while (enterMoreData == 'y' || enterMoreData == 'y');
Console.ReadKey();
}
public static int GetData(out string centreName, out string city, out decimal ticketPrice, string[] dArray, int[] adultVisitors, decimal[] totalRevenue)
{
int i,
loopCnt;
Console.Clear();
Console.Write("Name of Centre: ");
centreName = Console.ReadLine();
Console.Write("City: ");
city = Console.ReadLine();
Console.Write("Ticket Price: ");
string inValue = Console.ReadLine();
ticketPrice = Convert.ToDecimal(inValue);
Console.Write("How many records for {0}? ", centreName);
string inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out loopCnt) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for number of records");
for (i = 0; i < loopCnt; i++)
{
Console.Write("\nDate (mm/dd/yyyy): ");
dArray[i] = Console.ReadLine();
if (dArray[i] == "")
{
Console.WriteLine("No date entered - " +
"Unknown recorded for visits");
dArray[i] = "Unknown";
}
Console.Write("Number of One-Day Adult Visitors: ");
inValue1 = Console.ReadLine();
if (int.TryParse(inValue1, out adultVisitors[i]) == false)
Console.WriteLine("Invalid data entered - " +
"0 recorded for adults visited");
}
return i;
}
}
I had it working before I made some changes to my program, but now it keeps coming up blank when I run it. Any idea why?
Without having the complete code it's difficult to debug this for you.
But here's a suggestion that came up when I was reading the start of your question:
It seems like the basic gist would be to use a Dictionary<DateTime, int> which would store the number of visits for each day.
Then you can use a simple LINQ query to get the smallest value:
dictionary.OrderBy(kvp => kvp.Value).First()
Of course, you can use a complex class in place of the int and store more data (location, price of admission for that day, adult visits, etc.).
class CenterVisitations
{
internal int Visitations { get; set; }
internal decimal TicketPrice { get; set; }
internal string Location { get; set; }
//add other stuff here, possibly create another class
//to store TicketPrice, Location and other static center data
//and create a reference to that here, instead of the above
//TicketPrice and Location...
}
Then you can define your dictionary like so:
Dictionary<DateTime, CenterVisitations>
And query it almost the same was as last time:
dictionary.Order(kvp => kvp.Value.Visitations).First();
Sorting and selecting would work the same way. Additionally you could add a .Where query to set a range of dates which you want to check:
dictionary.Where(kvp => kvp.Key < DateTime.Today && kvp.Key > DateTime.Today.AddDays(-7)) will only look for the last weeks worth of data.
It also seems you're keeping your data in separate arrays, which means querying it is that much harder. Finally, consider converting dates into DateTime objects rather than strings.
My code below works fine but what I want to do is to display the summary in ascending order according to its OrderNum. I tried to put Array.Sort(order[x].OrderNum) but error cannot convert from int to System.Array. Any suggestions on how I can sort this? Thank you very much!
using System;
class ShippedOrder
{
public static void Main()
{
Order[] order = new Order[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order();
Console.Write("Enter order number: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the order number " + order[x].OrderNum + " is a duplicate. " + "\nPlease re-enter: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name: ");
order[x].Customer = Console.ReadLine();
Console.Write("Enter Quantity: ");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nSummary:\n");
for (x = 0; x < order.Length; ++x)
{
Array.Sort(order[x].OrderNum); //This line is where the error is located
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total;
}
Console.WriteLine("\nTotal for all orders is Php" + grandTotal.ToString("0.00"));
Console.Read();
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order() { }
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice + 4;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("ShippedOrder " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "Shipping is Php4.00\n" + " The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
Just use Linq:
order = order.OrderBy(x => x.OrderNum).ToArray();
While looking this link, found that Array.Sort will not take integer as parameter.
You have to pass all the data as Array object.
Try the following:
order.Sort( delegate (Order o1, Order o2) {
return o1.OrderNum.CompareTo(o2.OrderNum);
});