Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

85
Visualizações
Flatten list of lists containing a single item

I have a list that consists of lists containing up to a single string, for example:

var fruits = new List<List<string>>
{
    new List<string>(),
    new List<string> { "Apple" },
    null,
    new List<string> { "Banana" },
};

I would like to extract the strings from the list above, not allowing the lists containing the strings to have more than one item. That is, I need to have the following result:

{ "Apple", "Banana" }

So far I have been trying the following:

var result = fruits
    .Where(x => x != null)
    .Select(x => x.SingleOrDefault())
    .Where(x => x != null);

Is there a simpler solution to do this?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If I understand correctly you want to select all unique items in lists to a single list, you can use SelectMany() and Distinct() for that:

fruits.Where(x=> x != null).SelectMany(x=> x).Distinct();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda