Blankman
Blankman

Reputation: 267290

How to order by a property in a collection using linq?

I have a link sequence, and I want to order by User.Name (its a sequence of users).

How can I do that?

Also, if I want to remove any users with User.Count = 0 can I do that in the same query?

Upvotes: 1

Views: 279

Answers (1)

dtb
dtb

Reputation: 217401

IEnumerable<User> result = from user in users
                           where user.Count != 0
                           orderby user.Name
                           select user;

or

IEnumerable<User> result = users.Where(user => user.Count != 0)
                                .OrderBy(user => user.Name);

where users is a IEnumerable<User> (such as a List<User>).

This selects all users where user.Count != 0 and returns them ordered by user.Name.

Note that the original collection users remains unchanged.

Upvotes: 10

Related Questions