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?
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.
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.
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.
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();
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.
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