Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression for getting indexes of list items conditionally

Tags:

c#

lambda

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?

like image 222
Jimmy Avatar asked Nov 13 '10 21:11

Jimmy


People also ask

Can we use dynamic in lambda expression?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

Can we write a Parameterless lambda expression?

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");


1 Answers

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.

like image 198
Jon Skeet Avatar answered Nov 07 '22 04:11

Jon Skeet