首页 > 解决方案 > 使用带有 OR 语句的 Find All 过滤列表

问题描述

if (product_search.Text.Trim() != "")
{
    filteredProductsList = filteredProductsList
      .FindAll(s => s.product.Contains(product_search.Text.Trim().ToUpper()));
}

如果产品包含搜索的文本,我有上面的代码过滤产品列表。但是,我希望此文本框在Product或上进行过滤Barcode。如果有办法运行FindAll()但有一个OR声明。那么过滤到产品是否包含搜索的文本或条形码?

标签: c#listfindall

解决方案


像这样的东西:

// Search if product_search is not all whitespace string
if (!string.IsNullOrWhiteSpace(product_search.Text)) {
  // let's extract a local  variable (readability) 
  string toFind = product_search.Text.Trim();

  // it seems you want case insensetive search: let's specify it clearly:
  // StringComparison.CurrentCultureIgnoreCase
  // trick: IndexOf(..., StringComparison.CurrentCultureIgnoreCase) >= 0 since
  //        we don't have appropriate Contains
  // Finally, you want || - either product or barCode should contain toFind
  filteredProductsList = filteredProductsList
    .FindAll(item => 
       item.product.IndexOf(toFind, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
       item.barCode.IndexOf(toFind, StringComparison.CurrentCultureIgnoreCase) >= 0);
}

推荐阅读