Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Object and Selecting based on custom priority

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.


1 Answers

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();
}
like image 188
Amy B Avatar answered Jul 21 '26 12:07

Amy B