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

StackOverflow https://stackoverflow.com/questions/23672072

  •  23-07-2023
  •  | 
  •  

Question

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.

Was it helpful?

Solution 2

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.

OTHER TIPS

Use the .Skip(int) function if you want to start it at an exact offset, e.g.

return _properties.Skip(start_index).Sele[...]

If you want to return the index of the first occuring element, use .IndexOf() instead of .Any()

Since .IndexOf() returns -1 on no results, if you wish to return a null, you can do so by checking if the value returned equals -1:

if (result == -1)
    return null;

Please notice that you will have to make the return value a nullable int (= int?) for it to be able to return a null.

EDIT

My apologies, IEnumerables do not have the IndexOf() function as there's no index in one. You can try using .TakeWhile(bool).Count() to get an index. An alternative would be to use .ToList().IndexOf(), if you really want to use it, but it'd be much slower since you'd have to parse the entire object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top