vendredi 17 avril 2015

Sorting a list of objects of multiple data types

I have this class in my code



class Stock
{
public DateTime Date;
public string Day;
public double Open, Close, Diff;
public int Volume;

public Stock(double open, double close, double diff, int volume, string day, DateTime date)
{
this.Open = open;
this.Close = close;
this.Diff = diff;
this.Volume = volume;
this.Day = day;
this.Date = date;
}
}


In another class i want to create a bubble sort that will sort a List of Stocks (List<Stocks>) passed to it, i am having multiple issues with this the main problem is the data types, its not easy comparing two values when they could be a string, int, double or DateTime. I have done it with a method that uses TryParse to check for valid data type, but im looking for a nice clean solution, this is my attempt so far



public void BubblesortBy(int sortBy, List<Stock> Stocks)
{

Type objType = typeof(Stock);
FieldInfo[] fields = objType.GetFields();

Stock temp = null;
int loopCount = 0;
bool doBreak = true;

for (int i = 0; i < Stocks.Count; i++)
{
doBreak = true;
for (int j = 0; j < Stocks.Count - 1; j++)
{
if (Compare(fields[sortBy - 1].FieldType.ToString(), fields[sortBy].GetValue(Stocks[j]), fields[sortBy].GetValue(Stocks[j+1])))
{
temp = Stocks[sortBy + 1];
Stocks[sortBy + 1] = Stocks[sortBy];
Stocks[sortBy] = temp;
doBreak = false;
}
loopCount++;
}
if (doBreak) { break; /*early escape*/ }
}
}


The int passed to it determines whether to sort by, which is why i am using reflection so the variables are accessible by numbers.



  1. Date

  2. Day

  3. Open

  4. Close

  5. Difference

  6. Volume






Aucun commentaire:

Enregistrer un commentaire