按一个或多个参数制作过滤器

Make Filter by one or more parameters

我有List<Book> Books

public class Book
{
    public string Name { get; set; }
    public string Author { get; set; }
    public string Category { get; set; }
    public string Language { get; set; }
    public DateTime Publication_date { get; set; }
    public string ISBN { get; set; }
}

试过了,但只有所有参数都匹配才有效

foreach (var item in Books)
{
    if ((!string.IsNullOrEmpty(name) && item.Name == name) 
      && (!string.IsNullOrEmpty(author) && item.Author == author) 
      && (!string.IsNullOrEmpty(category) && item.Category == category)
      && (!string.IsNullOrEmpty(language) && item.Language == language) 
      && (Publication_date.HasValue && item.Publication_date == Publication_date) 
      && (!string.IsNullOrEmpty(ISBN) && item.ISBN == ISBN))
    {
        Console.WriteLine(item);
    }
}

如何根据一个或多个参数进行筛选?就像我只输入“名称”和“语言”一样,它会打印出两个参数都匹配的书(如果字符串为 null 或为空,则应跳过参数)

谢谢)

像这样尝试,使用 OR (||) 运算符

foreach (var item in Books)
{
    if ((!string.IsNullOrEmpty(name) && item.Name == name) 
      || (!string.IsNullOrEmpty(author) && item.Author == author) 
      || (!string.IsNullOrEmpty(category) && item.Category == category)
      || (!string.IsNullOrEmpty(language) && item.Language == language) 
      || (Publication_date.HasValue && item.Publication_date == Publication_date) 
      || (!string.IsNullOrEmpty(ISBN) && item.ISBN == ISBN))
    {
        Console.WriteLine(item);
    }
}

您希望它采用一种形式,其中每个条件 returns 如果为空则为真,或者如果匹配则为真。基本上 null/empty 意味着任何东西都是匹配的

喜欢

(string.IsNullOrEmpty(name) || item.Name == name) 

然后一起 && 他们

foreach (var item in Books)
{
    if ((string.IsNullOrEmpty(name) || item.Name == name) 
      && (string.IsNullOrEmpty(author) || item.Author == author) 
      && (string.IsNullOrEmpty(category) || item.Category == category)
      && (string.IsNullOrEmpty(language) || item.Language == language) 
      && (!Publication_date.HasValue || item.Publication_date == Publication_date) 
      && (string.IsNullOrEmpty(ISBN) || item.ISBN == ISBN))
    {
        Console.WriteLine(item);
    }
}

你可以做的更清楚一点

bool IsMatchForFilter(string filter, string value) 
       => string.IsNullOrEmpty(filter) || filter == value;

然后做

if(
   IsMatchForFilter(name, item.Name) 
   && IsMatchForFilter(author, item.Author)
  ...

逻辑有点复杂,但通过使用 continue 变得更简单。

foreach (var item in Books)
{
    if (!string.IsNullOrEmpty(name) && item.Name != name) continue;
    if (!string.IsNullOrEmpty(author) && item.Author != author) continue;
    if (!string.IsNullOrEmpty(category) && item.Category != category) continue;
    if (!string.IsNullOrEmpty(language) && item.Language != language) continue;
    if (Publication_date.HasValue  && item.Publication_Date != Publication_Date) continue;
    if (!string.IsNullOrEmpty(ISBN) && item.ISBN!= ISBN) continue;

    Console.WriteLine(item);
}