我有以下功能搜索课程'文本匹配的属性值,如果其中任何一个匹配,则返回true。
private static List<Func<Type, string>> _properties;
private static Type _itemType;
public static bool Match(string searchTerm)
{
bool match = _properties.Select(prop => prop(_itemType)).Any(value => value != null && value.ToLower().Contains(searchTerm.ToLower()));
return match;
}
_properties列表是DataGrid列上绑定属性的顺序。 _itemType是类类型。
我想要做的是,继续搜索文本,但是,另外更改它以便它将从列表中的特定属性的索引开始并返回第一个属性的索引匹配它来或无效。
该功能的开头如下:
public static int Match(int start_index, string searchTerm)
可以帮助找出实现这一目标的最佳方法。
答案 0 :(得分:3)
如果要以精确的偏移量启动它,请使用.Skip(int)
功能,例如
return _properties.Skip(start_index).Sele[...]
如果要返回第一个出现元素的索引,请使用.IndexOf()
而不是.Any()
由于.IndexOf()
在没有结果时返回-1,如果你想返回一个null,你可以通过检查返回的值是否等于-1来实现:
if (result == -1)
return null;
请注意,您必须使返回值为nullable int(= int?
)才能返回null。
修改的
我很抱歉,IEnumerable
没有IndexOf()
功能,因为其中没有索引。您可以尝试使用.TakeWhile(bool).Count()
来获取索引。
另一种方法是使用.ToList().IndexOf()
,如果你真的想使用它,但由于你必须解析整个对象,因此它会慢得多。
答案 1 :(得分:1)
这样做你想要的吗?
public static int? Match(int start_index, string searchTerm)
{
var wanted = _properties
.Select((prop,i) => new { Index = i, Item = prop(_itemType) })
.Skip(start_index)
.FirstOrDefault(value => value.Item != null && value.Item.ToLower().Contains(searchTerm.ToLower()));
return wanted==null ? null : (int?)wanted.Index;
}