Linq查询过滤器

本文关键字:过滤器 查询 Linq | 更新日期: 2023-09-27 18:04:54

我有一个Linq查询,奇怪的是,虽然它不断返回一个序列不包含任何元素。数据确实存在,我看到一个计数:

  • 制造商:One Element
  • 人:三百十四记录

下面的查询返回错误:

var people = Query<PersonModel>(getPeople)
     .Where(model => model.FirstName.Contains(search) || 
          model.LastName.Contains(search)) ||
          model.ManufacturerId.Contains(manufacturers.First().ManufacturerId.ToString()))
     .ToList();

我的理解是.Where将根据集合的结果进行过滤。为什么错误不包含序列中的元素?

堆栈跟踪:

在System.Linq.Enumerable

。第一个[TSource](IEnumerable 1 source)
at ...<>c__DisplayClass5.<btnSearch_Click>b__4(... model) in ...aspx.cs:line 70 at System.Linq.Enumerable.WhereListIterator
)System.Collections.Generic.List 1..ctor(IEnumerable (1 collection)
在System.Linq.Enumerable。列表[TSource](IEnumerable ' 1源)在...对象发送者,EventArgse)…aspx.cs:行在System.Web.UI.WebControls.Button。OnClick(EventArgs e)在System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串eventArgument)System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串eventArgument)System.Web.UI.Page.RaisePostBackEvent (IPostBackEventHandlersourceControl,字符串事件参数)System.Web.UI.Page。RaisePostBackEvent (NameValueCollection postData)
System.Web.UI.Page.ProcessRequestMain(布尔includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Linq查询过滤器

试试这个

var people = Query<PersonModel>(getPeople)
 .Where(model => model.FirstName.Contains(search) || 
      model.LastName.Contains(search) ||
      (manufacturers != null && manufacturers.Any(a => a.ManufacturerId == model.ManufacturerId)))
 .ToList();

嗯,最初关于异常的罪魁祸首是First()的评论是正确的。我可以通过以下方式规避异常:

 var manufacturers = Build<ManufacturerModel>(getManufacturer)
     .Where(model =>
          model.ManufacturerName.Contains(search));
 if(manufacturers.Any())
      manufacturer = manufacturers.FirstOrDefault().ManufacturerId.ToString();

然后我在if中包装了我的初始查询,以测试是否尝试在manufacturer上过滤的值。这个解决方案有效,但并不理想,有一个更好的替代方案可能更理想。

另一个例子是:

people = Build<PersonModel>(getPeople);
foreach (var person in people)
{
     var m = person.ManufacturerIDs.Split(',')
         .Where(id => (manufacturers != null && manufacturers.Any(item => String.Compare(item.ManufacturerId.ToString(), id, true) == 0))).ToList();
     var r = person.ManufacturerIDs.Split(',')
          .Where(id => (repAgencies != null && repAgencies.Any(item => String.Compare(item.RepAgencyId.ToString(), id, true) == 0))).ToList();
     if (m.Any() || r.Any())
          filter.AddRange(people.Where(model => model.PersonId == person.PersonId).ToList());
}

然后在该循环之外,只需对人执行.Where并将所述结果添加到filter列表中。