How to Filter a 2-dimensional List?

Viewed 86

I'm trying to filter the following list:

List<List<int>> list = new List<List<int>>()
{
  new List<int>(){1,2,3,4,5},
  new List<int>(){6,7,5,4,5},
  new List<int>(){1,3,3,222,1}
}

My filter condition should be: "include only odd numbers", so my list shouldn't have any even numbers after the filter is applied.

My Attempt:

list = list.Where(x => x.Where(y => y%2 == 1).ToList()).ToList()

Desired Output:

List<List<int>> list = new List<List<int>>()
{
  new List<int>(){1,3,5},
  new List<int>(){7,5,5},
  new List<int>(){1,3,3,1}
}

I know how to use Linq on single-dimensional collections, but not sure how to make this one work.

Any ideas?

1 Answers

You may use the following:

list = list.Select(x => x.Where(i => i % 2 == 1).ToList())
           .Where(x => x.Any())
           .ToList();

Here, we're using Select() to iterate the elements of the outer list, then using Where() to filter the inner list. After that, we call Where() on the outer list to filter out empty inner lists. That last part is optional; feel free to remove it if you need to keep empty lists.

Note: As @Dmitry stated in the comments, it's probably better to use i % 2 != 0 if you want to keep negative odd numbers.

Related