Fazendo um List.Find no .Net

Written by oraculum. Posted in .NET, Frameworks / DBAs | Tagged: , ,

Fazendo um List.Find no .Net

Published on Julho 26, 2009 with Sem Comentários

Agumas coisinhas legais para fazermos com o list<> do .net.

Veja como é fácil fazermos uma busca em uma List<>, veja abaixo uma classe chamada Person

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Person
{
    public string LastName;
    public string FirstName;
 
    public static Predicate<Person> FindPredicate(Person person1)
    {
        return delegate(Person person2)
        {
            return person1.LastName == person2.LastName
                && person1.FirstName == person2.FirstName;
        };
    }
 
    public static Predicate<Person> FindByLastNamePredicate(string lastName)
    {
        return delegate(Person person)
        {
            return person.LastName == lastName;
        };
    }
}

Acrescentar uma pessoa se ela não estiver na lista:

1
2
3
4
if (myPeeps.Find(Person.FindPredicate(peepToFind)) == null)
{
    myPeeps.Add(peepToFind);
}

Buscar uma pessoa com o nome de Gump:

1
Person foundPeep = myPeeps.Find(Person.FindByLastNamePredicate("Gump"));

Retornando uma lista de resultados:

1
List<Person> aList = myPeeps.FindAll(FindPredicate(Pessoa));

Acerca oraculum

Browse Archived Articles by oraculum

Sem Comentários

There are currently no comments on Fazendo um List.Find no .Net. Perhaps you would like to add one of your own?

Leave a Comment