Andrey Sanches

é MVP em ASP/ASP.NET e escreve sobre desenvolvimento WEB com tecnologias Microsoft
Posted: by

Comments

Suleyman V said:

Thank you very much.

Your example is very useful and easy to understand :)

# April 27, 2007 7:45 AM

Israel Aece said:

In C# 3.0 is much more simple :)

Person result =

    myList.Find(p => p.Name == "Israel");

# May 28, 2007 12:47 PM

Derek said:

What is this syntax in VB.net?

//find a specific object

Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });

# June 17, 2007 7:55 PM

Steve Kumbsky said:

Thanks for this tip! I was struggling with a way to do a Find using an outside value on an object property in the List. This is the answer.

# June 26, 2007 5:31 PM

Vic Moran said:

I'm sorta using something like this (except I defined a separate delegate method and passed the pointer to Find).  

The problem is, in order to get at the ID, you have to explicitly instantiate a specific object type (Person) in order to use this method; defeats the purpose uf using generics, doesn't it! And what's with the delegate, anyway?  Give me a way to specify a key or let "Find" search without the need for a delegate (very hokey).  I know it's hard to code a generic "Find" because the generic list can take any type, but use Reflection, something; once the list is typed, "Find" should know how to handle it.  There are other ways to check for reference type equality.

The other issue with List<T> is that "IndexOf" doesn't work with objects (assuming all ref types) either.

I know they improved performance (mostly) and added type safety over ArrayList, but we need a better generic list construct.

# October 26, 2007 2:10 PM

Ramesh said:

Thank you very much. I have been searching for this and atlast I found here.

# December 13, 2007 6:50 PM

Dennis Decoene said:

In your example, you are search for ID 1. This 1 is a fixed value. How would make it so the search parameter is dynamic?

# December 19, 2007 4:51 AM

Zack Stauber said:

This is a great example.  Thanks!

# December 24, 2007 12:53 PM

Bas said:

Just wanted to say that this a very good example and as I am using Visual Studio 2008, the code by Israel works perfectly for me. Cheers!

# January 4, 2008 9:05 AM

renato said:

VERY GOOD EXAMPLE!! CHEERS!

# July 25, 2009 4:06 PM

Vivek Chauhan said:

what i do when i need to find the record corresponding two value like ID and name both in above example.

# September 16, 2009 9:56 AM

andrey said:

Hi Vivek,

Take a look at the following C# code :

Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1 && p.Name == "AndreySanches"; });

Let me know if you have any other questions

# September 16, 2009 10:55 AM

Laercio Guerço Rodrigues said:

Tive a mesma impressão, mas na verdade, foi uma satisfação em perceber que teríamos a partir de LINQ, algo como já víamos em Java com JPA e EJB3, ou ainda, a mais tempo, DataSnap em Delphi.

Acredito realmente que com LINQ To Entitie estabilizado, teremos uma corrida para esta tecnologia.

# September 17, 2009 6:36 AM

andrey said:

Olá Laercio,

Exatamente. Sempre fui meio "assim" para esses frameworks, mas na vdd o que faltou era dar uma olhada mais a fundo e entender os benefícios. Foi uma quebra de paradígmas :) abs

# September 17, 2009 7:28 AM

Ranjit said:

While this rapid fire code is nice, it leaves more to be desired. One, rarely would a dynamic code search for id = 1 and name as Andrey. In real situations when the name is not known at design time, how do you search for a person with a name that is known at run time? Secondly, I wish someone pointed out the code in vb.net.

# September 17, 2009 1:42 PM

andrey said:

Hi Ranjit,

Actually this code is just an example. In the real situation you would need to replace number "1" and string "AndreySanches" for a local variable.

Eg.

int id = Convert.ToInt32(txtCustomerId.Text);

string name = txtCustomerName.Text;

Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == id && p.Name == name; });

Thanks for your comments

# September 17, 2009 2:08 PM

Khoa Do said:

List<T>.Find() is not so cryptic after reading your post.

Thanks for sharing your expertise.

# September 18, 2009 4:32 AM

Leandro said:

Olá, tudo bem? Estou tentando fazer um select com o left join e não estou conseguindo fazer a iteração, como faço para isso? Ocorre o seguinte erro:

LINQ to Entities does not recognize the method '<>f__AnonymousType9`5[System.Int32,System.String,System.String,System.Int32,System.String] ElementAtOrDefault[<>f__AnonymousType9`5](System.Linq.IQueryable`1[<>f__AnonymousType9`5[System.Int32,System.String,System.String,System.Int32,System.String]], Int32)' method, and this method cannot be translated into a store expression.

Obrigado desde já,

Leandro

# October 19, 2009 10:03 AM

andrey said:

Olá Leandro, como vai ?

Poderia por favor postar seu código ?

abs

# October 19, 2009 11:17 AM

Anders said:

Thanks for this :) Helpful in order to understand delegates.

# October 21, 2009 7:42 AM

Emiliano Eloi Silva Barbosa said:

 E ai Andrey, beleza?

Minha questão está em como colocar essa pesquisa em uma Classe de negócio. Qual o tipo de retorno que devo utilizar uma vez que não consigo usar o List<Produto>, pois ele retorna uma Entidade 'Nova' ou mesclada. Observe Meu código:

   public List<Produto> RecuperarTodosProdutos()

   {

       var query = from regProduto in dconBlogDemo.Produtos

                   join regCategoriaProduto in dconBlogDemo.CategoriaProdutos

                   on regProduto.CategProdID equals regCategoriaProduto.CategProdID

                   select new { ID = regProduto.ProdutoID,

                                Descricao = regProduto.Descricao,

                                Categoria = regCategoriaProduto.Descricao};

       return query.ToList();

   }

Muito obrigado!

# October 29, 2009 3:57 PM

andrey said:

Olá Emiliano,

Não entendi o problema em colocar esse método em uma classe de negócio. Não há problema algum em retornar uma lista de Produtos List<Produto>. Você está recebendo alguma mensagem de erro nessa sua query ? Ao invés de usar o "select new" tente usar somente "select regProduto;"

abs

# October 29, 2009 4:12 PM

Emiliano Eloi Silva Barbosa said:

  Buenas!

  Se eu utilizar o regProduto eu retorno um Objeto Produto, dessa forma não vou ter a Descrição da categoria do produto. Na verdade o que eu quero fazer é colocar a query linq que você fez nesse post dentro de uma classe de negócio e setar o dataSource do gridView da seguinte forma:

beProduto produto = new beProduto();

GridView1.DataSource = produto.RecuperaTodosProdutos();

Valew!

# October 30, 2009 7:30 AM

andrey said:

Olá Emiliano,

Então o que você quer fazer é exatamente o que eu fiz no post. Qual o problema que você está tendo em retornar a lista de produtos exibindo a categoria de cada produto?

Como você mesmo fez, deu nome à cada campo de retorno e é exatamente esse nome que você vai usar de bind nas colunas da GridView.

O seu código está correto, ainda não entendi qual dificuldade você está tendo em colocar esse método numa classe de negócios.

abs

# October 30, 2009 7:47 AM

Shilpi said:

Thanks a lotttttttttttttttttttttttt

# November 4, 2009 12:38 AM

kiran said:

Can u tell me it is work for datetime also.

i ahve the same class above and contains one more property as  

private DateTime _joinDate;

 public DateTime  JoinDate

       {

           set { _joinDate = value; }

           get { return _joinDate; }

       }

now i want to find employee who joined recently??

can you show me how this works?

thanks in advance

Kiran .

# November 9, 2009 5:17 AM

Hal said:

Well done!

# November 9, 2009 9:17 AM

andrey said:

Hi Kiran,

You can use the "JoinDate" property to search the objects.

e.g.

Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == id && p.JoinDate == #yourdateobject#; });

Let me know if you need anything else.

Thanks

# November 9, 2009 9:28 AM

michael said:

GREAT SIMPLE TUTORIAL

# December 9, 2009 8:52 AM