-1

I have class named : Book and in this class I have 2 properties : BookName and BookDate like this :

    public class Book
{
    public string BookName
    {
        get;
        set;
    }
    public DateTime BookDate
    {
        get;
        set;
    }
}

and in the Main I created an instance of it and in the foreach loop I can see the items . like this :

        List<Book> books = new List<Book>();

    DateTime firstBookTime = new(2011, 02, 02, 2, 2, 2);
    DateTime secondBookTime = new(2012, 02, 02, 2, 2, 2);
    
      Book firstBook = new()
    {
        BookName = "firstBook",
        BookDate = firstBookTime
    };
    Book secondBook = new()
    {
        BookName = "secondBook",
        BookDate = secondBookTime
    };
    
    books.Add(firstBook);
    books.Add(secondBook);

            foreach (Book bookList in books)
    {
       
        Console.WriteLine
            (
            $"name is : {bookList.BookName}" +
            $" and date : is {bookList.BookDate} "
            );

    }

everything is fine I can see he items with console . but I cant sort them , I tried these but no good resault :

    books.Sort((x, y) => string.Compare(x.BookName, x.BookName));

    books = books.OrderBy(item => item.BookDate).ToList();

    books.Sort();

How can I sort the BookName alphabetically and BookDate base on newer date ?

thanks

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
behnami454
  • 77
  • 8

2 Answers2

6

The easiest is LINQ. But it requires to create a new list as opposed to List.Sort:

books = books
    .OrderBy(book => book.BookName)
    .ThenByDescending(book => book.BookDate)
    .ToList();

This orders by BookName and in case of duplicate names it takes the newer book.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
3

To sort items within list in place, use Sort:

books.Sort((left, right) => {
  // First compare BookNames
  int sort = left.BookName.CompareTo(right.BookName);

  // If Book Names are equal we compare BookDate
  // in descendent order (note left and right swapped) 
  if (sort == 0)
    sort = right.BookDate.CompareTo(left.BookDate);

  return sort;
});
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215