I have a List<bool>
. I need to get the indexes of top n items where item value = true.
For example the following list items(bool)
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
How can I write a lambda for this?
In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.
Lambda expressions can be parameterless or have one or more parameters. The following code snippet illustrates a lambda expression that doesn't have any parameters. () => Console. WriteLine("This is a lambda expression without any parameter");
Well, 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);
(Obviously fill in the appropriate bit of the Where
clause. If it's just a List<bool>
it may just be x => x.value
.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With