1

I have a class Users:

class User
{
    public string Name { get; set; }
    public Address Address { get; set; }
    public DateTime Birthday { get; set; }
}

Then I have a list of users like List<User> users. And I meet with the problem which sounds "How to order list by Name length string property?

I've tried something like this:

users.OrderBy(user=>user.Name.Length);

and unfortunately it didn't work.

Thanks for the reply and best regards.

krypru
  • 1,692
  • 3
  • 22
  • 29
  • It should have worked. What is you result ? – rducom Feb 10 '15 at 08:32
  • 5
    Daft question perhaps, but have you tried assigning the result back to the collection? users = users.OrderBy(user=>user.Name.Length); – LDJ Feb 10 '15 at 08:32
  • Probably a duplicate http://stackoverflow.com/questions/188141/list-orderby-alphabetical-order?rq=1 – Kavindu Dodanduwa Feb 10 '15 at 08:34
  • @LDJ is right, but also convert result to List. `users = users.OrderBy(user=>user.Name.Length).ToList();` – Farhad Jabiyev Feb 10 '15 at 08:34
  • I think you would have to do it this way: users = users.toList().OrderBy(user=>user.Name.Length); – Rob Feb 10 '15 at 08:47
  • @LDJ I'm kinda nocfuesd, it's obvious answer. I missed that. But about what Dmitry Bychenko has written what is better practise? Use Sort or OrderBy method? For me the OrderBy constrution with lambda it's more clear and readble. – krypru Feb 10 '15 at 09:00

1 Answers1

2

Providing that the list doesn't have null users as well as null names:

users.Sort((Comparison<User>) ((left, right) => 
  return left.Name.Length - right.Name.Length;
));

Note, that the code sorts an existing list users, while OrderBy creates a new collection:

users = users
  .OrderBy(user => user.Name.Length)
  .ToList();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Thanks for the answer. I wonder what is better practise? Use Sort or OrderBy method? For me the OrderBy constrution with lambda it's more clear and readble – krypru Feb 10 '15 at 09:02
  • 2
    @vindemi: `Sort()` is a better solution here, since `OrderBy` *creates a new collection* which means additional resouces (time and memory) using. – Dmitry Bychenko Feb 10 '15 at 09:21