C# 编写linq查询的较短方法

C# 编写linq查询的较短方法,c#,.net,linq,C#,.net,Linq,需要为下面的代码编写一个较短的linq查询 enrolledPortfoliosVM = enrolledPortfoliosVM .Where(ep => ep.ProductCategories != null && ep.ProductCategories .Where(pc => pc.ProductTypes != null && pc.ProductTypes .Where(pt =>

需要为下面的代码编写一个较短的linq查询

enrolledPortfoliosVM = enrolledPortfoliosVM
    .Where(ep => ep.ProductCategories != null && ep.ProductCategories
        .Where(pc => pc.ProductTypes != null && pc.ProductTypes
            .Where(pt => pt.Benefits != null && pt.Benefits
                .Where(b => b.EndDate != null && b.EndDate > currentDate)
                .ToList().Count > 0)
            .ToList().Count > 0)
        .ToList().Count > 0)
    .ToList();
为了澄清,这将返回Enrolled PortfolioStypeVM的集合。以下是MS SQL server的northwind数据库示例:

Customers
    .Where(c => c.Orders
        .Any(o => o.ShippedDate > new DateTime(1997,1,1)))
生成以下SQL:

-- Region Parameters
DECLARE @p0 DateTime = '1997-01-01 00:00:00.000'
-- EndRegion
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [Customers] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Orders] AS [t1]
    WHERE ([t1].[ShippedDate] > @p0) AND ([t1].[CustomerID] = [t0].[CustomerID])
    )

为什么需要编写更短的Linq查询?如果它起作用,那么它就起作用了。如果你只是想润色/提高代码的可读性,那么这也许是一个更好的地方来寻求注释和响应。与其缩短它,不如尝试用其他方式来改进它。例如,
ToList()。不是因为
Any()
更短,而是因为它更好地表达了“notempty”的概念。另外,如果你有一个罐子,里面有一些硬币,你要数多少硬币才能知道它不是零?你不需要那些空检查,但无论如何这是一个奇怪的查询。Change
ep=>ep.ProductCategories!=null&&ep.ProductCategories
ep=>ep.ProductCategories?.Where(…
@CetinBasoz)为什么说不需要
null
检查?调用
。Where
(或
null
对象上的任何
)都会抛出
ArgumentNullException
。例如:
Enrolled>Enrolled PortfoliosVM=new List{new SomeType{ProductCategories=null}}
我没有投反对票,但可能是因为你忽略了@RufusL的问题,为什么你说可以忽略空检查,然后继续写了一个答案,没有它们。问题仍然是为什么你认为可以调用
.Any()
在一个可能为空的对象上。@itsme86,我没有忽略它。对于Any,它是否为空并不重要。本质上我们是在问“有没有?”.我们不会问是否有可能出现任何无效。这并不能解释否决票的原因。我的猜测是,被否决的人甚至不理解它,只是因为她/他可以。这是这样的缺点,一个人可以否决票,只是因为她/他不理解,可以不做任何解释。我认为你有误解站在空检查旁边。有空集合(即
.Any()
检查)与不存在的集合(即空检查)不同。如果您不相信我,请尝试
List List=null;bool Any=List.Any()
然后看看会发生什么。@itsme86,用空列表代替空集合是不现实的。谁会给列表编写代码来实现这一点。源代码很可能是一个数据库,其中有空集合,而不是空列表。如果你想用空列表代替,并且是纯粹的,你可以添加空检查。我的观点基于真实世界的美国年龄,使用数据库。
-- Region Parameters
DECLARE @p0 DateTime = '1997-01-01 00:00:00.000'
-- EndRegion
SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]
FROM [Customers] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Orders] AS [t1]
    WHERE ([t1].[ShippedDate] > @p0) AND ([t1].[CustomerID] = [t0].[CustomerID])
    )