J'ai créé quatre méthodes pour obtenir de travail du filtre en fonction de plusieurs paramètres:
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);
}
Je pense qu'il pourrait être fait avec une seule méthode, mais malgré de nombreuses tentatives, je ne sais pas comment le gérer. Ce sont mes objets utilisés dans l'exemple:
//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; }
}
Je vous serais reconnaissant de toutes les idées
Mise à jour
Merci à vous, @Abanslash! J'ai également ajouté le texte de la chaîne de filtre et s'est terminé avec le code comme ceci:
private string searchString1 = "";
static bool FilterHash<T>(IEnumerable<string> list, T viewModel, Func<string, bool> p)
{
if (!list.Any())
{
return true;
}
return list.Any(p);
}
public bool TestFilter(AreaPlaceCoordinate apc)
{
bool textEmpty = (string.IsNullOrWhiteSpace(searchString1));
List<string> names = new() { apc.AreaName, apc.PlaceName, apc.CoordinateName };
bool filterText = textEmpty ? true : names.Any(n => n.Contains(searchString1, StringComparison.OrdinalIgnoreCase));
bool areaSelector(string str) => apc.AreaName.Contains(str);
bool coordinateSelector(string str) => apc.CoordinateName.Contains(str);
bool placeSelector(string str) => apc.PlaceName.Contains(str);
return FilterHash(AreaHash, apc, areaSelector) && FilterHash(CoordinateHash, apc, coordinateSelector) && FilterHash(PlaceHash, apc, placeSelector) && filterText;
}