How to sort List with LINQ using Nested Property

QA User 1 Reputation point
2021-09-22T03:29:22.623+00:00

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 author Name. Thanks.

Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2021-09-22T07:19:44.63+00:00

    @QA User , I recommend that you could sort the Authors by name first the, you could sort the first Author by Name.

    Here is a code example you could refer to.

    foreach (var item in books)  
            {  
                item.Authors = item.Authors.OrderBy(i => i.Name).ToList();  //Sort the Authors by the Name   
            }  
            var list = books.OrderBy(i => i.Authors.FirstOrDefault().Name).ToList();  //Sort the books by the First Author Name  
            foreach (var item in list)  
            {  
                Console.WriteLine(item.Id+"**"+item.Title);  
                foreach (var au in item.Authors)  
                {  
                    Console.WriteLine(au.Name);  
                    Console.WriteLine("*******");  
                }  
            }  
    

    Result:

    134157-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.