如何修改lambda语句以从列表索引位置开始并返回该位置

时间:2014-05-15 07:41:42

标签: c# propertyinfo

我有以下功能搜索课程'文本匹配的属性值,如果其中任何一个匹配,则返回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)

可以帮助找出实现这一目标的最佳方法。

2 个答案:

答案 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;
    }
  1. 使用带有第二个索引参数的select并将其存储在 匿名类型。
  2. 然后跳过指定的数字 &#39; START_INDEX&#39 ;.
  3. 然后搜索剩余部分,如果找到,则返回 原始索引。