I’m looking on how to sort a list effectively using weighted values.
Each item has an id, name and filepath. Each item also has a list of values which are assigned a percentage, showing how relevant they are to each value.
I need the list to be sorted so that the items which are at the top end of the list are the ones which are the most relevant to the current parameters.
Lets say,
Item One:
- A: 50, B: 30, C : 20, D : 10
- X : 50, Z :20
Item Two:
- A:100, B:0, C:0, D:0
- X:0, Z:100
And my parameters are A and Z. Clearly Item Two should be at the top of my list as it’s the most relevant item. But how would I go about implementing this?
Bonus: Would be nice to be able to have a slight randomisation as well, I don’t want to be served the definitive relevant item each time.
Thanks
Assuming you know your weighting function, you could use Linq to Objects:
In this example,
SortingValuewould be a property on the object that encapsulates the attributes in your question and would implement your algorithm.Sample algorithm for SortingValue:
You could use a Dictionary to hold relevance percentages
Then, your “current parameters” could be used as keys to the Dictionary to get the relevant weighting: