有没有办法从Linq的部分前缀列表中找到索引,如:
List<string> PartialValues = getContentsOfPartialList();
string wholeValue = "-moz-linear-gradient(top, #1e5799 0%, #7db9e8 100%)";
int indexOfPartial = PartialValues
.IndexOf(partialPrefix=>wholeValue.StartsWith(partialPrefix));
Run Code Online (Sandbox Code Playgroud)
不幸的是,IndexOf()不接受lambda表达式.是否有类似的Linq方法?
Tim*_*ter 25
你根本不需要LINQ,List<T>有一个方法FindIndex.
int indexOfPartial = PartialValues
.FindIndex(partialPrefix => wholeValue.StartsWith(partialPrefix));
Run Code Online (Sandbox Code Playgroud)
为了完整起见,您可以使用LINQ,但这不是必需的:
int indexOfPartial = PartialValues
.Select((partialPrefix , index) => new{ partialPrefix , index })
.Where(x => wholeValue.StartsWith(x.partialPrefix))
.Select(x => x.index)
.DefaultIfEmpty(-1)
.First();
Run Code Online (Sandbox Code Playgroud)
蒂姆有最正确的答案(/sf/answers/1385477201/),但如果你真的想要一个扩展方法,IEnumerable<T>那么你可以用这样的方法来做:
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;
}
Run Code Online (Sandbox Code Playgroud)