Vytvořil jsem čtyři metody, aby se pracovní filtr na základě několika parametrů:
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);
}
Myslím, že to může být provedeno s jednou metodou, ale i přes mnoho pokusů nevím, jak to zvládnout. To jsou moje objekty použité v příkladu:
//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; }
}
Ocenil bych nějaké nápady
Aktualizace
Děkuji, @Abanslash! Také jsem přidal řetězec, text, filtr a skončil s kódem, jako je tento:
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;
}