-1

How can I sort a list by id in c# that contains Book items?

static List<Book> sorted = new List<Book>();

public string title { get; set; }
public string summary { get; set; }
public int id { get; set; }
public int numberofauthors { get; set; }
public string author {get; set;}

But I want to sort the whole list and not only the sorted[k].id column.

Servy
  • 202,030
  • 26
  • 332
  • 449
GeralexGR
  • 2,973
  • 6
  • 24
  • 33
  • What do you mean by "sort the whole list and not only the `id` column"? When you sort it on `id`, you *do* sort the entire list, where for each element of the result the `id` field is equal or greater than the `id` property of the previous item. – CodeCaster May 24 '13 at 15:54
  • 2
    Have you tried anything so far? If so, what specifically have you tried? What was the result of that attempt? Have you done some research online as to how others have attempted to solve similar problems? If so, how have other people attempted to solve this problem? Have you tried to adapt those solutions to your situation? – Servy May 24 '13 at 15:54
  • Searching "[C#] How to sort a list of objects by property" would have been a great way to save time :) The answers are already out there. – Elle May 24 '13 at 15:57
  • possible duplicate of [C#.NET :How to Sort a List by a property in the object](http://stackoverflow.com/questions/3309188/c-net-how-to-sort-a-list-t-by-a-property-in-the-object) – Servy May 24 '13 at 16:03
  • You might try any of the answers described in this question especially if you are uncomfortable with LINQ. As your question is a bit ambiguous. http://stackoverflow.com/questions/3309188/c-net-how-to-sort-a-list-t-by-a-property-in-the-object – jth41 May 24 '13 at 15:56

3 Answers3

2

Try LINQ:

var sortedList = sorted.OrderBy(x => x.id).ToList();
Rafal
  • 1,081
  • 8
  • 10
0
sorted.OrderBy(book => book.id);

Is this what you're thinking of? Or perhaps this? http://msdn.microsoft.com/en-us/library/w56d4y5z.aspx

I'm sure this question has been answered plenty of times. Have you tried Google?

mason
  • 31,774
  • 10
  • 77
  • 121
0

You can use List.Sort which does sort this list instead of Enumerable.OrderBy + ToList what creates a new list. Therefore you need to implement IComparable<Book>

class Book : IComparable<Book>
{
    public string title { get; set; }
    public string summary { get; set; }
    public int id { get; set; }
    public int numberofauthors { get; set; }
    public string author { get; set; }

    public int CompareTo(Book other)
    {
        if (other == null) return 1;

        return id.CompareTo(other.id);
    }
}

Now this works:

books.Sort();

Without changing your class you could also use List.Sort with a custom Comparison<Book>:

books.Sort((b1, b2) => b1.id.CompareTo(b2.id));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939