Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list by field (C#)

Tags:

c#

list

sorting

I have class like:

class SortNode
{
    public Int32 m_valRating = 0;

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

and some list refSortNodeList:

List<SortNode> refSortNodeList = new List<SortNode>();

Random refRandom = new Random();

for (int i = 0; i < 100; ++i)
{
    refSortNodeList.Add(new SortNode(refRandom.Next(-10, 30)));
}

foreach (var varSortNode in refSortNodeList)
{
    Console.WriteLine("SortNode rating is {0}", varSortNode.m_valRating);
}

How to sort easily my refSortNodeList by m_valRating field? Or maybe I need to use some another List class?

like image 950
Edward83 Avatar asked Mar 28 '11 15:03

Edward83


3 Answers

list.Sort((x,y) =>
    x.m_valRating.CompareTo(y.m_valRating));
like image 98
Marc Gravell Avatar answered Nov 11 '22 08:11

Marc Gravell


In-place:

refSortNodeList.Sort(
  (x, y) =>
    x == null ? (y == null ? 0 : -1)
      : (y == null ? 1 : x.m_valRating.CompareTo(y.m_valRating))
);

Creating a new enumeration:

var newEnum = refSortNodeList.OrderBy(x => x.m_valRating);

Creating a new list:

var newList = refSortNodeList.OrderBy(x => x.m_valRating).ToList();

In-place is fastest and most memory efficient, but no good if you want to also retain the old list.

The next is faster than the last and gives results as they go, but you have to re-do the sort to use it again, in which case the third is the one to go for.

like image 20
Jon Hanna Avatar answered Nov 11 '22 08:11

Jon Hanna


Use Linq order by.

var mySortedList = refSortNodeList.OrderBy(x => x.m_valRating);

Here is a real live example where I am pulling a list from a database but it is exactly the same concept.

 vendorProducts = (from vp in db.COMPANIES_VND_PRODUCTS
                    join p in db.CT_CT_INV_CLASSES on vp.CLASS_ID equals p.CLASS_ID
                    join m in db.CT_CT_MODALITY_CODES on vp.MODALITY_ID equals m.MODALITY_ID
                    where vp.COMPANY_ID == companyId
                    select new ProductTypeModality
                    {
                      Active = p.ACTIVE.Equals("Y") ? true : false,
                      BioMedImaging = p.BIOMED_IMAGING,
                      Code = p.CLASS_CODE,
                      Description = p.DESCRIPTION,
                      Id = p.CLASS_ID,
                      PricingMargin = p.PRICING_MARGIN,
                      ModalityCode = m.MODALITY_CODE,
                      ModalityId = m.MODALITY_ID,
                      VendorId = companyId
                    }).OrderBy(x => x.Code).ToList<ProductTypeModality>();
like image 14
Kenn Avatar answered Nov 11 '22 08:11

Kenn