编写linq查询的更短方法

时间:2019-06-14 18:58:12

标签: c# .net linq

需要为下面的代码编写一个较短的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();

1 个答案:

答案 0 :(得分:2)

var  portfolios = enrolledPortfoliosVM
                    .Where(ep => ep.ProductCategories
                        .Any(pc => pc.ProductTypes
                            .Any(pt => pt.Benefits
                                .Any(b => b.EndDate > currentDate)
                                )
                            )
                        )
                    .ToList();

为澄清起见,这将返回任何enrolledPortfoliosTypeVM的集合。这是MS SQL Server罗斯文数据库的示例:

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])
    )