Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexOf with Linq, accepting lambda expression

Tags:

c#

lambda

linq

Is there a way to find the index from list of partial prefixes with Linq, something like:

List<string> PartialValues = getContentsOfPartialList();
string wholeValue  = "-moz-linear-gradient(top,  #1e5799 0%, #7db9e8 100%)";
int indexOfPartial = PartialValues
                      .IndexOf(partialPrefix=>wholeValue.StartsWith(partialPrefix));

Unfortunately, IndexOf() doesn't accept lambda expression. Is there a similar Linq method for this?

like image 452
Annie Avatar asked Nov 05 '13 15:11

Annie


People also ask

Can you use lambda expression instead of LINQ query?

So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.

What does => mean in LINQ?

the operator => has nothing to do with linq - it's a lambda expression. It's used to create anonymous functions, so you don't need to create a full function for every small thing.

Is LINQ faster than lambda?

In some cases LINQ is just as fast if not faster than other methods, but in other cases it can be slower. We work on a project that we converted to linq and the data lookup is faster but the merging of data between two tables is much slower.


2 Answers

You don't need LINQ at all, List<T> has a method FindIndex.

int indexOfPartial = PartialValues
    .FindIndex(partialPrefix => wholeValue.StartsWith(partialPrefix));

For the sake of completeness, you can use LINQ, but it's not necessary:

int indexOfPartial = PartialValues
  .Select((partialPrefix , index) => (partialPrefix , index))
  .Where(x => wholeValue.StartsWith(x.partialPrefix))
  .Select(x => x.index)
  .DefaultIfEmpty(-1)
  .First();
like image 171
Tim Schmelter Avatar answered Oct 06 '22 04:10

Tim Schmelter


If you have List<T>, see accepted answer.

In case you have IEnumerable (or other collection that implements it) instead of List, you can use following LINQ code:

int index = PartialValues.TakeWhile(partialPrefix=> ! wholeValue.StartsWith(partialPrefix)).Count();

Pay attention at the negation operator (!) in lambda expression: lambda expression should return true for elements that do NOT match your condition.

Code will return number of elements (e.g. index will point at position immediately after the last element) if no elements match the condition.

like image 34
nevermind Avatar answered Oct 06 '22 03:10

nevermind