简体   繁体   中英

How can I sort a list using a method that uses the list's item as a parameter?

Let's say that I have the following list and method:

List<myObject> myList = (some function that prepopulates myList);

I would like to sort myList in descending order using a method that I created:

int sortByThisValue(myObject obj)
{
    int someInteger;
    // Operations on obj that generates a value for someInteger
    ...
    return someInteger;
}

The first solution that comes to mind is to create a sorted Dictionary and then extract the values as a list. However, this fails when two objects generate the same someInteger because a dictionary must have a unique set of keys. What is the best way sort this list?

Have you tried using LINQ ?

myList = myList.OrderByDescending(p=>p.someInteger).ToList();

or Asecending

myList = myList.OrderBy(p=>p.someInteger).ToList();

Alternatively, if you want to do manual sorting, you can implement IComparer interface. This may be required if the sorting is complex and not easily achieved using LINQ .

class MyListSorter : IComparer<myObject>
{
    public int Compare(myObject x, myObject y)
    {
        if (x.Num < y.Num) return 1;
        if (x.Num > y.Num) return -1;
        return 0;
    }
}

myList.Sort(new MyListSorter());

LINQ makes this easy:

// Method group conversion
List<myObject> sorted = myList.OrderByDescending(SortByThisValue).ToList();

// Lambda expression
List<myObject> sorted = myList.OrderByDescending(x => SortByThisValue(x))
                              .ToList();

Note that this does not sort the list in-place; it creates a new list. If you don't need to actually create a new list, just remove the ToList call at the end, eg

foreach (MyObject item in myList.OrderByDescending(x => SortByThisValue(x))
{
    // Do something
}

It's well worth looking into LINQ - it makes all kinds of data querying really simple.

If you absolutely need to sort in-place, you could use:

myList.Sort((x, y) => SortByThisValue(y).CompareTo(SortByThisValue(x)));

(Note the use of y followed by x here - that's what's reversing the "natural" ordering so that you get the values in descending order.)

It's uglier than the LINQ version though, IMO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM