Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

79
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!