sorting values in a generic list

G

Guest

Hi I have a generic list populated by a structure and sorts the contents of
the list based on the day and project # that is part of the structure. I
would like to modify it to also sort on the start time as the third sort
parameter? thanks.

public class Comparer : IComparer<mergeoutstruct>
{

public int Compare(mergeoutstruct a, mergeoutstruct b)
{
int result = DateTime.Compare(a.day, b.day);
if (result == 0)
{
result = a.projectnum.CompareTo(b.projectnum);
}
return result;
}

}


public struct mergeoutstruct
{
public Int32 projectnum;
public DateTime day;
public TimeSpan time;
public Double timeout;
public DateTime starttime;
public DateTime endtime;
}

Comparer comp = new Comparer(); //sorts by day and project #.
merglist.Sort(comp.Compare);
 
N

Nicholas Paldino [.NET/C# MVP]

Paul,

You just have to add one more check, like so:

public class Comparer : IComparer<mergeoutstruct>
{
public int Compare(mergeoutstruct a, mergeoutstruct b)
{
int result = DateTime.Compare(a.day, b.day);
if (result == 0)
{
result = a.projectnum.CompareTo(b.projectnum);

// New check.
if (result == 0)
{
// Compare the start time.
result = a.starttime.Compare(b.starttime);
}
}
return result;
}
}

You probably want to compare against the end time as well, in the event
that the start times are the same.
 
G

Guest

it works, thanks!
--
Paul G
Software engineer.


Nicholas Paldino said:
Paul,

You just have to add one more check, like so:

public class Comparer : IComparer<mergeoutstruct>
{
public int Compare(mergeoutstruct a, mergeoutstruct b)
{
int result = DateTime.Compare(a.day, b.day);
if (result == 0)
{
result = a.projectnum.CompareTo(b.projectnum);

// New check.
if (result == 0)
{
// Compare the start time.
result = a.starttime.Compare(b.starttime);
}
}
return result;
}
}

You probably want to compare against the end time as well, in the event
that the start times are the same.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top