Taian
Taian

Reputation: 319

Linq - Filter list property that is inside another list by a list of strings

I have a list of an object called Ocorrencia and it has a property called Tecnicos that is a list of the object OcorrenciaTecnico. This object has a propert called Nome that it a String. I want to filter the list of Ocorrencia by this last property (Nome), by a list of String's.

Too complex to me. How can I achieve this?

I've tried this:

ocorrencias = ocorrencias.Select(
    x => x.Tecnicos.Where(
        y => ocorrenciaFiltro.TecnicosFiltro.Any(
            z => z.Equals(y.Nome))));

But I'm getting an error:

Cannot implicitly convert type "System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<MasterCoin.Models.OcorrenciaTecnico>>" to "System.Collections.Generic.IEnumerable<MasterCoin.Models.Ocorrencia>". An explicit conversion exists (are you missing a cast?)

Upvotes: 0

Views: 307

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

I guess you confused Select (a projection) and Where (a filter). Try this:

var filteredOcorrencias = ocorrencias.Where(
    x => x.Tecnicos.Any(
        y => ocorrenciaFiltro.TecnicosFiltro.Contains(y.Nome))).ToList();

Upvotes: 3

Romain
Romain

Reputation: 810

How about that ?

var nomes = new List<string> {"Taian", "Taian2"};
var allTaian = Ocorrencia.Where(o => o.Tecnicos.Any(t => nomes.Contains(t.Nome)));

Upvotes: 1

Related Questions