Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Filter a list with a different IEnumerable<bool>

I cannot find out how to filter an array/list from another list array: I was looking for something like this:

IEnumerable<bool> Filter = new[] { true, true, false,true };

IEnumerable<string> Names = new[] { "a", "B", "c", "d" };

List<string> NameFiltered = Filter
    .Where(c => c == true)
    .Select(x => Names)
    .ToList();
like image 898
Yoyo Avatar asked Feb 19 '26 23:02

Yoyo


2 Answers

In general case (both Names and Filter are IEnumerable<T> only) I suggest Zip:

List<string> NameFiltered = Names
  .Zip(Filter, (name, filter) => new {
    name = name,
    filter = filter, })
  .Where(item => item.filter)
  .Select(item => item.name)
  .ToList();

If Filter is in fact an array (..Filter = new[]...) Where will do:

List<string> NameFiltered = Names
  .Where((name, index) => Filter[index])
  .ToList();
like image 184
Dmitry Bychenko Avatar answered Feb 21 '26 13:02

Dmitry Bychenko


var NameFiltered = Enumerable.Range(0, Names.Count)
                             .Where(n => Filter[n])
                             .Select(n => Names[n])
                             .ToList();
like image 40
jmcilhinney Avatar answered Feb 21 '26 12:02

jmcilhinney