1

Consider the following pseudo code:

List<Person> People = new List<Person>();
int score;

...

foreach (Person p in People){

score = scoreFunc(p);

???

}

Question - how can I sort a list of Person objects by the score ? In case you are wondering, I would not want to make the score a property of Person because it will be different for the same Person in different circumstances and is not logically a property of Person.

1
  • "score" could of course be made an array or be added to a collection as need be Commented Mar 16, 2012 at 4:26

1 Answer 1

5

Sorting happens using a delegate/class that can compare two persons - there is no mandate that you need to compare them using single attribute. For example

People.Sort((p1,p2)=>scoreFunc(p1)-scoreFunc(p2));

EDIT:

If you wish to sort the whole list by a score then this will be the only way (you may change the sorting algorithm but comparison would not change because score is the sorting key). Now above would probably compute the score for some persons multiple time - so one of the optimization could be to cache the person score. For example, scoreFunc can check in the cache (dictionary) to see if score has been already computed or not.

Further optimizations can happen based on your actual requirements and scoring function implementation. For example, assume that you have 10000 persons and you are probably interested in top 20. Assume that person's age and educational qualifications contributes bulk of the score while there are 20 other attributes that do minor contribution. So you can do multi-pass sorting - the first pass may use a score based on only two factors to determine say top 500 persons and then you apply detailed scoring to do get actual top 20.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, do you think you could expand on your answer a bit, how would you recommend sorting the whole list using this comparison ?
@Ivan, I am not 100% sure what you are trying to ask here ... but nevertheless, see my edit!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.