tags:

views:

62

answers:

2

I have a LINQ statement that generate an anonymous type, for example:

BookID, AuthorID, [Authors]*

Authors return a IEnumerable which also contains many authors, it has 2 columns: AuthorID and AuthorName

For example:

1 | 32 | 12, Author 1

     20, Author 3

     32, Author 19

How can I re-order the Authors object so that [32, Author 19] is on top, as:

1 | 32 | 32, Author 19

     12, Author 1

     20, Author 3

Thank you very much, Kenny.

A: 

You can just recreate object of anonymous type, because its readonly property can not be changed.

Something like this:

  record =
    new {
      record.BookId,
      record.AuthorId,
      Authors =
        record.Authors.Where(author => author.Id==32).Union(
          record.Authors.Where(author => author.Id!=32))
    };
Alex Kofman
A: 

As Alex says, you'll just recreate the anonymous type. To geth a specific author to the top of the list, you can use orderby clause (or OrderBy extension method), which I think, is a bit easier then using Where and Union:

new { 
  ...
  Authors = from a in record.Authors
            orderby a.AuthorID == 32 descending
            select a 
};

The only trick is that you can use boolean value (AuthorID == 32) as a key for the ordering. In this way, you'll first get all elements for which the predicate returns true (the one with ID=32) and then all other values (for which the predicate returned false).

Tomas Petricek