sorting - Which Collection framework to sort Objects -


here class

class emp {       string firstname;       string lastname;       int sal;       ----------- } 

here have list of 100 employees, want sort objects based on salary , first name & last name. using collection frame work how can ? related how dictionary works ??

.net has several collection task.

list

you can create list entities , sort them method sort. example how sort on salary (assuming fields public):

list<emp> empcollection= new list<emp> {     new emp { sal = 1000, firstname = "chris", lastname = "bakker" },     new emp { sal = 1500, firstname = "bea", lastname = "smith" },     // etc. }; empcollection.sort((a,b) => a.sal.compareto(b.sal)); 

pro's , con's:

  • pro: resort collection on key.
  • con: although list sorted, cannot search through if faster on key.

sorteddictionary

you use sorteddictionary. dictionary combination of keys , values. value, in case, employee. key element want items sorted on. example sort on first name:

sorteddictionary<string, emp> empcollection= new sorteddictionary<string, emp> {     {"chris", new emp { sal = 1000, firstname = "chris", lastname = "bakker" }},     {"bea", new emp { sal = 1500, firstname = "bea", lastname = "smith" }},     // etc. }; 

pro's , con's:

  • pro: once list sorted, queries keys pretty fast.
  • con: have add key seperately feels adding duplicate data.
  • con: cannot resort collection on key; have create new dictionary.

linq

you can use linq create newly created , sorted list:

list<emp> empcollection= new list<emp> {     new emp { sal = 1000, firstname = "chris", lastname = "bakker" },     new emp { sal = 1500, firstname = "bea", lastname = "smith" },     // etc. }; list<emp> sortedempcollection = empcollection.orderby(e => e.lastname).tolist(); 

pro's , con's:

  • pro: syntax easy understand.
  • con: newly created list created every time (more memory management).
  • con: although list sorted, cannot search through if faster on key.

Comments

Popular posts from this blog

java - Jmockit String final length method mocking Issue -

asp.net - Razor Page Hosted on IIS 6 Fails Every Morning -

c++ - wxwidget compiling on windows command prompt -