Home > Blockchain >  Possible to provide an instance delegate vs static in my C# class for use in Linq query?
Possible to provide an instance delegate vs static in my C# class for use in Linq query?

Time:01-15

Is there a simpler way to express this Func? Or to call it as an instance method, rather than static?

The goal is to eliminate all of the complexity of the search in the view/UI code ...

If I have a class (FilterDetail) with a set of bool values, grouped as strings for comparison to a list of items ... in a legacy database.

public IEnumerable<string> Locations => new List<string> { AsOne, AsTwo, AsThree, AsFour, AsFive, AsSix };

And I provide this ...

public static Func<FilterDetail, string, bool> LocationFilter = (item, loc) => 
    item.Locations.Any(x => x.Equals(loc, StringComparison.OrdinalIgnoreCase));

So in my view I can just:

 calls = calls.Where(x => FilterDetail.LocationFilter(Filter, x.Location_Abbr))

Is there a way, using Linq, to just use a function from the instance of FilterDetail (Filter)?

CodePudding user response:

Yes, you can use an instance method if you have an object available.

Assuming FilterDetail Filter is an object in scope, then

calls = calls.Where(x => Filter.LocationFilter(x.Location_Abbr));

The LocationFilter method would need to be changed:

public bool LocationFilter(string)
{
  return this.Locations.Any(x => x.Equals(loc, StringComparison.OrdinalIgnoreCase));
}
  • Related