This is my ugly code which needs to sort my data. I'm not really familiar with C# since actually I'm a Java programmer.
How could this code be rewritten without loosing performance? I know I could use reflection, but it is bad for performance.
sortings
is a list of the fields that have to be sorted and if it has to be ASC and DESC. leistungen
is the data to be sorted.
The classes:
public class Aufzeichnung
{
public string Mitarbeiter { get; set; }
public int Dauer { get; set; }
public double Kosten { get; set; }
}
public class Leistung
{
public int ID { get; set; }
public string Art { get; set; }
public string Angebot { get; set; }
public string Jahr { get; set; }
public string Berater { get; set; }
public string Assistent { get; set; }
public double Preis { get; set; }
public List<Aufzeichnung> Aufzeichnungen { get; set; }
}
public class LaufendeLeistung
{
public string Kunde { get; set; }
public List<Leistung> Leistungen { get; set; }
}
The algorithm:
internal static IEnumerable<A> Sort(List<A> leistungen, IEnumerable<Sorting> sortings)
{
for (int i = 0; i < sortings.Count(); i++)
{
var sort = sortings.ElementAt(i).Ascending ? 1 : -1;
if (sortings.ElementAt(i).Field.Equals("Kunde"))
{
leistungen.Sort((a,b) => string.Compare(a.Kunde,b.Kunde)*sort);
}
else
{
for (var j = 0; j < leistungen.Count(); j++)
{
if (sortings.ElementAt(i).Field.Equals("Leistung"))
{
leistungen[j].Leistungen.Sort((a, b) => string.Compare(a.Art, b.Art) * sort);
}
else if (sortings.ElementAt(i).Field.Equals("Angebot"))
{
leistungen[j].Leistungen.Sort((a, b) => string.Compare(a.Angebot, b.Angebot) * sort);
}
else if (sortings.ElementAt(i).Field.Equals("Jahr"))
{
leistungen[j].Leistungen.Sort((a, b) => string.Compare(a.Jahr, b.Jahr) * sort);
}
else if (sortings.ElementAt(i).Field.Equals("Berater"))
{
leistungen[j].Leistungen.Sort((a, b) => string.Compare(a.Berater, b.Berater) * sort);
}
else if (sortings.ElementAt(i).Field.Equals("Assistent"))
{
leistungen[j].Leistungen.Sort((a, b) => string.Compare(a.Assistent, b.Assistent) * sort);
}
else if (sortings.ElementAt(i).Field.Equals("Mitarbeiter"))
{
for (var k = 0; k < leistungen[j].Leistungen.Count(); k++)
{
if (leistungen[j].Leistungen[k].Aufzeichnungen != null)
{
leistungen[j].Leistungen[k].Aufzeichnungen.Sort((a, b) => string.Compare(a.Mitarbeiter, b.Mitarbeiter) * sort);
}
}
}
}
}
}
return leistungen;
}
Sorting
? (You can insert it in blockquote with a note to not review it, if you like.) \$\endgroup\$