Get the indexes of top n items where item value = true

Technology CommunityCategory: LINQGet the indexes of top n items where item value = true
VietMX Staff asked 3 years ago
Problem

I have a List<bool>. I need to get the indexes of top n items where item value = true.

10011001000

TopTrueIndexes(3) = The first 3 indexes where bits are true are 0, 3, 4 
TopTrueIndexes(4) = The first 4 indexes where bits are true are 0, 3, 4, 7 

Assuming you have some easily-identifiable condition, you can do something like this, which will work for any IEnumerable<T>:

var query = source.Select((value, index) => new { value, index })
                  .Where(x => x.value => Condition(value))
                  .Select(x => x.index)
                  .Take(n);

The important bits are that you use the overload of Select to get index/value pairs before the Where, and then another Select to get just the indexes after the Where… and use Take to only get the first n results.