简体   繁体   中英

How do I use OrderBy in my data on multiple fields?

Here is my code:

void Main() {
    List<Restaurant> RestaurantData = new List<Restaurant>();
}

class Restaurant {
    public int Id;
    public List<Complaint> ComplaintsList = new List<Complaints>();
}

class Complaint {
    public string Name;
    public string Address;
    public int Age;
    public DateTime ComplaintDate;
}

RestaurantData.OrderBy( x => x.ID, y => y.Complaint.Name).ToList();

I get an error on the y => y.Complaint.Name part. Can someone please help me understand why?

I want to order the data by Restaurant ID, and then by the Name of the Complaint.

After your edit, it appears that you want to Order the List first based on Restaurant.Id and then you want to order the inner list of Complaint based on Name . Following should do it.

List<Restaurant> newListOfRestaurant
        = RestaurantData
             .OrderBy(x => x.Id)
             .Select(r => new Restaurant
                  {
                      Id = r.Id,
                      ComplaintsList = r.ComplaintsList
                                        .OrderBy(c => c.Name)
                                        .ToList()
                  })
              .ToList();

(Old Answer)

You need to use Enumerable.ThenBy if you want order on multiple fields.

Performs a subsequent ordering of the elements in a sequence in ascending order according to a key.

RestaurantData  = RestaurantData.OrderBy( x => x.ID)
                                .ThenBy(y => y.Complaint.Name)
                                .ToList();

You need to assign the result back to the RestaurantData , otherwise it will not modify the existing list.

OrderBy does not modify collection ! Use ThenBy for multi field sorting

RestaurantData = RestaurantData.OrderBy( x => x.ID)
                       .ThenBy(y => y.Complaint.Name).ToList();

OrderBy is returing IOrderedEnumerable, read more about OrderBy

The OrderBy only accepts a single property expression. To do multiple ones you must ThenBy() with other property expressions. Do,

 var restaurantsByIdThenByComplaintName = 
     RestaurantData
           .OrderBy(restaurant => restaurant.ID)
           .ThenBy(restaurant => restaurant.Complaint.Name)
           .ToList();

Since this returns a different list, I would advice using a different variable to avoid mutating state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM