D
D
Dmitry Korolev2018-02-22 02:45:55
C++ / C#
Dmitry Korolev, 2018-02-22 02:45:55

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);
        }
    }

how to call the sort now i can't figure it out

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
freeExec, 2018-02-22
@adressmoeistranici

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);
}

And call list.Sort(SheduleCell.ReversSort);
Total:
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);
        }
    }

A
Alexander, 2018-02-22
@alexr64

https://support.microsoft.com/en-us/help/320727/ho...

E
eRKa, 2018-02-22
@kttotto

How to Sort a List<> by a Integer stored in the st...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question