How to get a list of values common to two lists with LINQ?

Asked

Viewed 1,000 times

1

I have two List,

the first, which is a list containing all the establishments available in the company, for example:


Estabelecimento 

Sigla - XPTO
Descricao - XPTO List 

Estabelecimento 

Sigla - RPTO
Descricao - RPTO List

Estabelecimento 

Sigla - GTOR
Descricao - GTOR List

The second owned establishments I can access, which in this case is just :


Estabelecimento 

Sigla - XPTO
Descricao - XPTO List 

I need to keep on the first list only the establishments I own on Monday.

Return from the first list would be :


Estabelecimento 

Sigla - XPTO
Descricao - XPTO List 

It would be the comparison of the first with the second, removing from the first what I don’t have on the second.

2 answers

1


I think what you want is intercession between the two lists

Use the method Intersect(). It returns a Ienumerable with the elements that exist simultaneously in both lists

lista1 = list1.Intersect(list2).ToList(); 

The Establishment class must provide its implementation of the methods GetHashCode() and Equals().

Or use a "Shop Comparator" that implements the interface IEqualityComparer<T>

lista1 = list1.Intersect(list2, new EstabelecimentosComparador()).ToList(); 
  • But it allows me to explore these elements and consider on the first list only what I have on the second?

  • After executing the code of the response to list1 you will only have the elements that exist simultaneously in the two lists

  • There is no way for me to make the intercession without having to implement the Iequalitycomparer interface?

  • Using this method has to implement. But even if you use another way you will always have to find a way to know when two objects Establishment are equal.

0

If there are two lists with the same type of object, it would not be just you assign to lista2 à lista1 nay?

todosEstabelecimentos = estabelecimentosComAcesso;
  • I need to remove what I won’t use on the first list.

  • In case I have in the second list? No, then remove, just shows what I have in the second.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.