Home > Mobile >  How to sort a List with LINQ using Nested Property
How to sort a List with LINQ using Nested Property

Time:09-22

I have a Json file with following data:

[ 
   { "Id": 510, "Title": "Big Start", "Author": [{ "AuthId": 7777, "Name": "Tom" }] },
   { "Id": 511, "Title": "Rising Tide", "Author": [{ "AuthId": 6666, "Name": "Bob" }] }
]

For the above, I have defined the following classes:

public class Book {
  public int Id { get; set; }
  public string Title { get; set; }
  public List<Author> Authors { get; set; }
 }
    
 public class Author {
  public int AuthId { get; set; }
  public string Name { get; set; }
 }

I have deserialized the json data using the following code:

List<Book> books;
 using (StreamReader sr = new StreamReader(Server.MapPath("...")))
 {
  books = JsonConvert.DeserializeObject<List<Item>>(sr.ReadToEnd()).ToList()
 }

Now I want to sort the list of books using author Name. I have tried the following:

var list = books.OrderBy(b => b.Author.OrderBy(a => a.Name)).ToList();

But I get the error message 'At least one object must implement IComparable'.

Can someone help me sort the above list using the nested author Name.

Thanks in advance.

CodePudding user response:

Thing is, Authors is a List, so which author name do we sort by? There might be many. "Book1, by Alfred and Zeus", "Book2 by Zigo, Mary and Ada" - how do these books sort? How do they sort if Book2 was by Ada, Mary and Zigo?

If there's only ever one author it's fairly simple

var list = books.OrderBy(b => b.Authors.First().Name).ToList();

As authors is a list you could also index it

var list = books.OrderBy(b => b.Authors[0].Name).ToList();

If there is ever more than one author you need to have a think about which author is used for sort.. If multiple authors contribute as tie breakers it gets more complex.. You could end up with a ThenBy that skips the first author etc, but then you need to consider if you're going to sort the authors too..

Remember that c# is case sens, so "bob" will sort after "Tom" and also the code above won't work if here are zero authors - you've implied there will always be one but if not, consider FirstOrDefault()?.Name??"" ..

..sometimes the simplest of questions leads to the most involved set of work! ;)

  • Related