Reorder LINQ result (take 1 row and move it to top) when a condition match
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
开发者_Go百科 20, Author 3
Thank you very much, Kenny.
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
).
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))
};
精彩评论