Linq查询过滤器

时间:2015-07-27 21:47:16

标签: c# asp.net asp.net-mvc linq webforms

我有一个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会根据集合的结果进行过滤。为什么错误不包含序列中的元素。

堆栈追踪:

  

at System.Linq.Enumerable.First [TSource](IEnumerable 1 source)
at ...<>c__DisplayClass5.<btnSearch_Click>b__4(... model) in ...aspx.cs:line 70 at System.Linq.Enumerable.WhereListIterator
1.MoveNext()at   System.Collections.Generic.List 1..ctor(IEnumerable 1集合)
  在System.Linq.Enumerable.ToList [TSource](IEnumerable`1 source)at   ... btnSearch_Click(Object sender,EventArgs   e)in   .... aspx.cs:行   69在System.Web.UI.WebControls.Button.OnClick(EventArgs e)at   System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串   eventArgument)at   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串   eventArgument)at   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler   sourceControl,String eventArgument)at   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
  在System.Web.UI.Page.ProcessRequestMain(布尔值   includeStagesBeforeAsyncPoint,Boolean includeStagesAfterAsyncPoint)

2 个答案:

答案 0 :(得分:1)

试试这个

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();

答案 1 :(得分:0)

好吧,关于异常的罪魁祸首的最初评论是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列表中。