question

QAUser-8126 avatar image
0 Votes"
QAUser-8126 asked JackJJun-MSFT commented

How to sort List with LINQ using Nested Property

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.






dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@QAUser-8126, May I know if you have got any chance to check my answer? I am glad to help if you have any others questions.

0 Votes 0 ·

I have not heard from you for a couple of days. Please let me know if there is anything that I can help in here.

0 Votes 0 ·

1 Answer

JackJJun-MSFT avatar image
0 Votes"
JackJJun-MSFT answered

@QAUser-8126 , 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.





image.png (2.4 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.