I have a custom priority array.
int[] priorities = { 866, 663, 855, 853, 854};
And I have this code to currently to sort through my list and pick the first based on the criteria.
var target = (from people in GetNearbyPeopleList()
where people.DistanceToTravel > 0 && people.ReachedDestination == false
orderby //not sure what to do here
select people).FirstOrDefault();
So I want to order by my custom priorities. Where people.currentlocation is ordered by my priorities array.
Do I do - ?
orderby priorities.Contains(people.currentlocation)
That's all I can think of, but it does not properly order by the order of my custom priorities. I want it to follow this order exactly:
int[] priorities = { 866, 663, 855, 853, 854};
So if location is 866, pick that one. I only want to select one and I want to select the first based on that priority list. If currentlocation == 866 does not exist, then pick 663 and so and so on.
If your values are fixed at compile-time... avoid the array and write:
orderby
people.currentLocation == 866 ? 1 :
people.currentLocation == 663 ? 2 :
people.currentLocation == 855 ? 3 :
people.currentLocation == 853 ? 4 :
people.currentLocation == 854 ? 5 :
6
If your values change at run-time, but the number of values has some fixed maximum, then write:
Person FindPriorityPerson(IQueryable<Person> query,
int p1 = 0, int p2 = 0, int p3 = 0, int p4 = 0,
int p5 = 0, int p6 = 0, int p7 = 0, int p8 = 0)
{
return query.OrderBy(person =>
person.currentLocation == p1 ? 1 :
person.currentLocation == p2 ? 2 :
person.currentLocation == p3 ? 3 :
person.currentLocation == p4 ? 4 :
person.currentLocation == p5 ? 5 :
person.currentLocation == p6 ? 6 :
person.currentLocation == p7 ? 7 :
person.currentLocation == p8 ? 8 :
9).FirstOrDefault();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With