My assignment is to have a functionality which enables app user to sort RegisteredUser
objects according to their filed/property values.
Assistant
class inherits RegisteredUser
. I would like somehow to be able to utilize lambdas
and LINQ
and to sort List<Assistants>
. Is there a way to achieve this?
public abstract class RegisteredUser
{
protected int id;
protected bool active;
protected string name;
//other fields and methods
public static IComparer sortUsersByName(Order order)
{
return (IComparer)new nameFieldComparator(order);
}
private class nameFieldComparator : IComparer
{
private Order direction;
public nameFieldComparator(Order direction)
{
this.direction = direction;
}
public int Compare(object x, object y)
{
if (x != null && y != null)
{
RegisteredUser user1 = (RegisteredUser)x;
RegisteredUser user2 = (RegisteredUser)y;
return (int)this.direction * String.Compare(user1.Name, user2.Name);
}
else throw new ArgumentNullException("Objects cannot be compared!");
}
}
}
My point of reference was How to use IComparer. I was trying different things, non worked.
Assistant a = new Assistant();
a.SetId(5);
a.Active = true;
a.Name = "asdasd";
Assistant f = new Assistant();
f.SetId(6);
f.Active = true;
f.Name = "asdf";
Assistant c = new Assistant();
c.Name = "a";
c.SetId(2);
List<RegisteredUser> l = new List<RegisteredUser>();
l.Add(a);
l.Add(f);
l.Add(c);
//list.Sort((x, y) => RegisteredUser.sortUsersByName()); of course, doesn't work...
List<Assistant> l = l.OrderBy() //tried bunch of ideas, but cannot get the syntax right
P.S. I am new to programming and c#