Search code examples
c#propertyinfo

How to modify lambda statement to start at lists index position and return that position


I have the following function that searches a class' property values for a text match, if any of them have a match it returns 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;
}

The _properties list is in the order of the bound properties on a DataGrid's columns. _itemType is the class type.

What I would like to do is, continue searching for the text, but, in addition change this so that it will start at a particular property's index in the list and return either, the index of the first property match it comes to or null.

The start of the function will look like so:

public static int Match(int start_index, string searchTerm)

Could use some help in figuring out the best way to accomplish this.


Solution

  • Does this do what you want ?

     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. Use select with the second index parameter and store it in an anonymous type.
    2. Then skip past the number specified in 'start_index'.
    3. Then search the remainder and if one is found, return the original index.