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

1

I have two List,

the first one, which is a list that contains 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 has the establishments that 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 properties that I own on the second.

Return from the first list would be:

Estabelecimento 

Sigla - XPTO
Descricao - XPTO List 

It would be the comparison of the first and second, removing from the first what I do not have in the second.

    
asked by anonymous 16.10.2017 / 22:36

2 answers

1

I think what you want is the intercession between the two lists

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

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

The Settlement class should provide its implementation of the GetHashCode() and Equals() methods.

Or use a "Site Comparer" that implements the IEqualityComparer<T>

lista1 = list1.Intersect(list2, new EstabelecimentosComparador()).ToList(); 
    
16.10.2017 / 23:05
0

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

todosEstabelecimentos = estabelecimentosComAcesso;
    
16.10.2017 / 22:56