Answer the question
In order to leave comments, you need to log in
How to use the Sort method of a list containing structure instances?
I am using a list of struct instances, I need to sort by value ascending or descending in the sheet using the sort method, but don't know how to do it
did icomparer implementation
public struct SheduleCell : IComparer
{
public string cell1;
public int cell2;
public SheduleCell(string param1, int param2)
{
cell1 = param1;
cell2 = param2;
}
public int Compare(object x, object y)
{
SheduleCell sc1 = (SheduleCell)x, sc2 = (SheduleCell)y;
return sc1.cell1.CompareTo(sc2.cell1);
}
}
Answer the question
In order to leave comments, you need to log in
First, you need to specify the type.
Then a simple one list.Sort();
will use the method
Let's say you have two methods of direct and reverse sorting, then you need to do it like this:
Have a methodpublic int CompareTo(SheduleCell sc)
public static int ReversSort(SheduleCell sc1, SheduleCell sc2)
{
return sc1.CompareTo(sc2) * (-1);
}
list.Sort(SheduleCell.ReversSort);
public struct SheduleCell : IComparable<SheduleCell>
{
public string cell1;
public int cell2;
public SheduleCell(string param1, int param2)
{
cell1 = param1;
cell2 = param2;
}
public int CompareTo(SheduleCell sc)
{
return cell1.CompareTo(sc.cell1);
}
public static int ReversSort(SheduleCell sc1, SheduleCell sc2)
{
return sc1.CompareTo(sc2) * (-1);
}
}
class Program
{
static void Main(string[] args)
{
var list = new List<SheduleCell>();
list.Add(new SheduleCell("X", 1000));
list.Add(new SheduleCell("B", 50));
list.Add(new SheduleCell("A", 100));
list.Add(new SheduleCell("C", 10));
list.Sort();
list.Sort(SheduleCell.ReversSort);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question