IndexOf with Linq accepting lambda expression

Is there a way to find an index from a list of Linq partial prefixes, for example:

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

Unfortunately, IndexOf() does not accept a lambda expression. Is there a similar Linq method for this?

+6
source share
4 answers

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

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

For completeness, you can use LINQ, but this is optional:

 int indexOfPartial = PartialValues .Select((partialPrefix , index) => new{ partialPrefix , index }) .Where(x => wholeValue.StartsWith(x.partialPrefix)) .Select(x => x.index) .DefaultIfEmpty(-1) .First(); 
+21
source

Tim has the most correct answer ( fooobar.com/questions/957430 / ... ), although if you really wanted to use the extension method for IEnumerable<T> , then you could do it with something like this

 public static int IndexOf<T>(this IEnumerable<T> source, Func<T, bool> predicate) { int index = 0; foreach (var item in source) { if (predicate(item)) return index; index++; } return -1; } 
+2
source

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

If you have IEnumerable (or another collection that implements it) instead of List , you can use the following LINQ code:

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

Note the negation operator (!) In the lambda expression: the lambda expression should return true for elements that DO NOT match your condition.

The code returns the number of elements (for example, the index will indicate the position immediately after the last element) if no elements match the condition.

0
source

You can use Enumerable.First

 string partialStr = PartialValues.FirstOrDefault(partialPrefix=>wholeValue.StartsWith(partialPrefix); int partialIndex = PartialValues.IndexOf(partialStr); 
-1
source

Source: https://habr.com/ru/post/957430/


All Articles