c# – OrderBy on lists<T>


I have a list<Pessoas> :

my people class:

public class Pessoas
    public String Nome { get; set; }
    public DateTime Nascimento { get; set; }

Theoretically you could do an OrderBy like this:

Pessoas.OrderBy(p => p.Nome);

But OrderBy does not appear to do this. Does my class have to 'be' or 'implement' something from IEnumerable ?


Yes, your class needs to implement the IEnumerable interface. In addition you have to make the System.Linq namespace available.

You are calling the Pessoas class, this means it will contain multiple people. So it seems to me that it makes sense to implement this interface. But if your intention is that this class represents only one person, then it wouldn't make sense and you would have to store the lists of people in another object, maybe a list, as shown in carlosfigueira's answer. If your intention is to use a list to hold people, then the list already implements IEnumerable and you would only need to use the LINQ namespace . But if so, the class name gives the wrong indication of what it represents.

You can't call this method from the class itself anyway, as in the example shown (I think). It has to be done with an instance. Maybe it's even an instance, since C# allows variables to have names like the types, but the name like that doesn't give a good indication of what it is. So you probably want is a var pessoas = new List<Pessoa>(); .

As LINQ is implemented on top of extension methods , these are only available when you do so explicitly. That is, LINQ methods will only be considered part of your object if they were made available with using , otherwise they do not appear in Intellisense as they are not part of the object, they are separate and optional auxiliary definitions.

Scroll to Top