I've created four methods to get working filter based on multiple parameters:
bool FilterAreas(AreaPlaceCoordinate apc)
{
if (!AreaHash.Any())
{
return true;
}
foreach (var _ in AreaHash.Where(h => apc.AreaName.Contains(h, StringComparison.OrdinalIgnoreCase)).Select(h => new { }))
{
return true;
}
return false;
}
bool FilterPlaces(AreaPlaceCoordinate apc)
{
if (!PlaceHash.Any())
{
return true;
}
foreach (var _ in PlaceHash.Where(h => apc.PlaceName.Contains(h, StringComparison.OrdinalIgnoreCase)).Select(h => new { }))
{
return true;
}
return false;
}
bool FilterCoordinates(AreaPlaceCoordinate apc)
{
if (!CoordinateHash.Any())
{
return true;
}
foreach (var _ in CoordinateHash.Where(h => apc.CoordinateName.Contains(h, StringComparison.OrdinalIgnoreCase)).Select(h => new { }))
{
return true;
}
return false;
}
bool Filter(AreaPlaceCoordinate apc)
{
return FilterCoordinates(apc)&&FilterPlaces(apc)&& FilterAreas(apc);
}
I think it could be done with one method, but despite of many attempts I don't know how to handle it. Those are my objects used in example:
//Hash
private IEnumerable<string> PlaceHash { get; set; } = new HashSet<string>() { };
private IEnumerable<string> AreaHash { get; set; } = new HashSet<string>() { };
private IEnumerable<string> CoordinateHash { get; set; } = new HashSet<string>() { };
public class AreaPlaceCoordinate
{
public int CoordinateId { get; set; }
public string CoordinateName { get; set; }
public int AreaId { get; set; }
public int PlaceId { get; set; }
public string AreaName { get; set; }
public string PlaceName { get; set; }
}
I would appreciate any ideas
CodePudding user response:
I believe what you want is to use are Predicates, you can have a generic method where you also pass the predicate. https://docs.microsoft.com/en-us/dotnet/api/system.predicate-1?view=net-6.0
If you are not very familiar with generic you can also specify the base type of the generic using where. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint
CodePudding user response:
In case you were not able to solve your issue with my previous comment here you go:
bool Filter<T>(IEnumerable<string> list, T apc, Func<string, bool> p)
{
if (!list.Any())
{
return true;
}
return list.Any(p);
}
public void testFilter()
{
AreaPlaceCoordinate coord = new AreaPlaceCoordinate();
Func<string, bool> selector = str => coord.AreaName.Contains(str);
this.Filter(PlaceHash, coord, selector);
}
You will have to modify a little bit for what you want to achieve and create the different selectors for your different filters.