【问题标题】:linq query only headers that have detailslinq 仅查询具有详细信息的标头
【发布时间】:2013-02-25 15:59:59
【问题描述】:

我正在尝试仅使用此 Lambda 语句获取具有详细信息的标头

list = list.Where(c=> c.CustomerSalesPeople.Count>0);

但是当我尝试返回结果时出现空异常

return list.OrderBy(c => c.CustomerName).ToList();

我已经单步执行了代码,并看到在我执行第一条语句后立即生成了 null 异常。有没有更好的方法来做到这一点。

编辑

我尝试了这些建议,但我仍然得到一个空值。我想我会尝试更好地解释。我需要一个匹配此查询的 Lambda 表达式

    SELECT *
  FROM [customer]
  where customer_record_id in (select distinct(customer_id)from customer_sales_person)

【问题讨论】:

  • 是 linq 到 objects/sql/entities 吗?
  • 它对对象的 linq。它们是 llblgen 实体。 LLBLGen 是 ORM

标签: c# linq lambda


【解决方案1】:
list = list.Where(c=>c.CustomerSalesPeople.Count>0).SingleOrDefault();

if(list!=null)
  return list.OrderBy(c=>c.CustomerName).ToList();

return list;

或者,如果您认为CustomerSalesPeople 可以为空,那么您可以这样做:

list = list.Where(c=>(c.CustomerSalesPeople==null) ||(c.CustomerSalesPeople.Count>0));

if(list!=null)
  return list.OrderBy(c=>c.CustomerName).ToList();

return list;

您也可以查看.DefaultIfEmpty() 扩展名。

Linq 提供了出色的扩展方法来应对找到空结果集的情况。 他们在这里:

  1. .FirstOrDefault()
  2. .DefaultIfEmpty()
  3. .SingleOrDefault()

更新:

这样做:

   List<int> uniqueIds= listOfCustomerSalesPerson.Select(s=>s.Id).ToList().Distinct();
   var requireListOfCustomers = GetAllCustomers().Where(s=>uniqueIds.Contains(s.id);

您也可以将这两个单独的调用嵌入到一个中。但是根据您使用的数据提供者的种类,它可能会给您一个错误,例如,“use only primitive types”。因此,单独的 id 列表。

例如,如果您使用的是 EntityFramework 5.0 和 SQL Server,则可以这样做。

myDbContext db= new myDbContext();
var requiredList = db.Customers.Where(s=>
                               (s.CustomerSalesPeople ==null)
                               ||
                               (s.CustomerSalesPeople.Select(o=>o.Id).Contains(s.Id))
                               ).ToList();

我假设,客户包含 List&lt;CustomerSalesPeople&gt; ,否则它可以是 db.CustomerSalesPeople

【讨论】:

  • 我将 Select 更改为 Any 并且效果很好。不要以为我知道将父变量 s 作为参数传递给子查询。谢谢
【解决方案2】:

您的集合中可以有空元素。尝试检查 where 语句中的空值

return list != null ? 
   list.Where(c=> c!=null && c.CustomerSalesPeople.Count>0).
   OrderBy(c => c.CustomerName).ToList()
   :null;

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2022-10-19
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多