有一种字符串方法:int IndexOf(string value)
。
我在Linq找不到更通用的东西,看起来应该是这样的:
static int IndexOf<T>(this List<T> source,List<T> value,Predicate<T> equality)
为什么Microsoft没有为我们提供通用字符串搜索功能?
答案 0 :(得分:0)
这听起来像是指List<T>.FindIndex()
。
- 编辑 -
任何 IEnumerable<T>
的更通用的方法是: -
public static int FindIndex<T>(this IEnumerable<T> source, Predicate<T> equality)
{
return source
.Select((item, index) => new {Item = item, Index = index})
.First(x => equality(x.Item)).Index;
}
答案 1 :(得分:0)
不是您问题的直接答案,但在某些情况下,您不需要查找索引,也可以使用带索引的函数。我认为我的解释并没有使它变得更简单,但也许一个例子会让它更清晰。
list.Select( (item, index) => /* do something here based on the index of the item */);
list.Where( (item, index) => /* filter the list based on the index and the item */);