Sort list by field (C#)

后端 未结 8 1231
一向
一向 2021-01-01 09:09

I have class like:

class SortNode
{
    public Int32 m_valRating = 0;

    public SortNode(Int32 valRating)
    {
        this.m_valRating = valRating;
    }         


        
8条回答
  •  心在旅途
    2021-01-01 09:43

    List refSortNodeList = new List ();
    
    Random refRandom = new Random ();
    
    for (int i = 0; i < 100; ++i) {
        refSortNodeList.Add (new SortNode (refRandom.Next (-10, 30)));
    }
    
    // Use this (Linq) if you're using .NET 3.5 or above.
    var sortedList = refSortNodeList.OrderBy (node => node.m_valRating);
    foreach (var varSortNode in sortedList) {
        Console.WriteLine ("SortNode rating is {0}", varSortNode.m_valRating);
    }
    
    // Use this otherwise (e.g. .NET 2.0)
    refSortNodeList.Sort (
        delegate (SortNode n1, SortNode n2) {
            return n1.m_valRating.CompareTo (n2.m_valRating);
        }
    );
    
    foreach (var varSortNode in refSortNodeList) {
        Console.WriteLine ("SortNode rating is {0}", varSortNode.m_valRating);
    }
    

提交回复
热议问题