Thank you very much.
Your example is very useful and easy to understand :)
In C# 3.0 is much more simple :)
Person result =
myList.Find(p => p.Name == "Israel");
What is this syntax in VB.net?
//find a specific object
Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });
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.
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.
Thank you very much. I have been searching for this and atlast I found here.
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?
This is a great example. Thanks!
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!
VERY GOOD EXAMPLE!! CHEERS!
what i do when i need to find the record corresponding two value like ID and name both in above example.
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
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.
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
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.
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
List<T>.Find() is not so cryptic after reading your post.
Thanks for sharing your expertise.
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
Olá Leandro, como vai ?
Poderia por favor postar seu código ?
abs
Thanks for this :) Helpful in order to understand delegates.
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!
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;"
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!
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.
Thanks a lotttttttttttttttttttttttt
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 .
Well done!
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
GREAT SIMPLE TUTORIAL