简体   繁体   中英

How to order a class list by a property within the classes

I want to be able to sort the following List<Player> by the integer within the Player class labelled rating . I want the highest rating to be the first index within my List of classes, a lot of the integers will be duplicates!

Initiation of the lists.

    public List<PriceCheckerParameters> _PriceCheckerList;
    public List<PriceCheckPlayerList> _PlayerList;
    private List<Player> _Players;

This is the class that I am storing a List of.

public class Player
{

    public enum RatingRank
    {
        Bronze,
        Silver,
        Gold,
    } 
    public int id { get; set; }

    public int nationId { get; set; }

    public int rating { get; set; }

    public RatingRank ratingLevel { get; set; }

    public string firstName { get; set; }

    public string lastName { get; set; }
}

This is the function where I am sorting the list and assigning it to another list of another irrelevant class.

    public async Task SetPlayerList()
    {
        //returns list of players and stores it to be sorted 
        _Players = await _ItemHandler.GetPlayerList();
        _PlayerList = new List<PriceCheckPlayerList>();

         //This is as much as I am able to get with my knowledge (I'm lacking)
        _Players = _Players.OrderBy()

        foreach (Player eap in _Players)
        {
            _PlayerList.Add(new PriceCheckPlayerList()
            {
                _Player = eap,
                SetYet = false,
                LastUpdated = DateTime.UtcNow, 
            });
        }
    }

I've tried reading looking for other answers but I am unable to wrap my head around the OrderBy or Sort functions.

EDIT: I see your answers but could someone please explain how exactly it works?

使用OrderBy Linq扩展名,可使最高排名保持在底部。

_Players = _Players.OrderBy(p=>p.rating).ToList();

As mentioned by all the previous answers, you can use the extension methods available to you on the List class. They are correct and will result in writing less code, and my preferred way as well, but since no one has mentioned or showed you how to do this in LINQ, I will place it here.

List<Player> _PlayerList = new List<Player>()
{
    new Player() { firstName = "TestName1", lastName = "TestSurname1", rating = 1 },
    new Player() { firstName = "TestName2", lastName = "TestSurname2", rating = 2 },
    new Player() { firstName = "TestName3", lastName = "TestSurname3", rating = 3 },
    new Player() { firstName = "TestName4", lastName = "TestSurname4", rating = 4 }
};

var sortedPlayers = from p in _PlayerList
                    orderby p.rating descending
                    select p;

foreach (var player in sortedPlayers)
{
    Console.WriteLine(player.firstName);
}

Here, I first initialized your list with some dummy data. As you can see, I then use LINQ to query your List of Players, and order the results in descending order.

This is the results produced. 在此处输入图片说明

If you would like to switch the results around in your list, simply change the 'descending' keyword in the LINQ query to 'ascending', different type of sorting. Here is an example of the opposite results.

var sortedPlayers = from p in _PlayerList
                    orderby p.rating ascending
                    select p;

This will be the results.

在此处输入图片说明

Here is a good place to get you started with LINQ.

这个怎么样?

_Players = _Players.OrderByDescending(player => player.rating).ToList();

The other answers before me are correct. I prefer this way because it uses one of the List constructors instead of calling .ToList():

//Ascending for first item in list to have the smallest rating value
List<Player> newList = new List<Player>(originalList.OrderByAscending(each => each.rating));

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