我看起来完全一样
How to efficiently query with filter on children at different levels?
但是“in lambdas”语法。
我真的需要这个,有人可以帮忙吗?谢谢!
答案 0 :(得分:4)
以下是您在查询语法和lambda语法中引用的帖子的代码段:https://stackoverflow.com/a/12324116/670028:
LINQ查询语法:
var listOfString = new List<string>() { "String1", "String2" };
var customers =
(
from a in session.Query<A>()
from b in a.B
from c in b.C
where a.Status == "Active"
&& listOfStrings.Contains( b.SomeField )
&& listOfStrings.Contains( c.someOtherField )
select a )
.ToList();
LINQ lambda语法:
var listOfString = new List<string>() { "String1", "String2" };
var customers =
(
session.Query<A>()
.SelectMany( a => a.B, ( a, b ) => new { a, b } )
.SelectMany( @t => b.C, ( @t, c ) => new { @t, c } )
.Where( @t => a.Status == "Active"
&& listOfStrings.Contains( b.SomeField )
&& listOfStrings.Contains( c.someOtherField ) ).
Select
( @t => a ) )
.ToList();
正如您所看到的,它不像LINQ查询语法那样“干净”,因为每次使用.SelectMany()方法时都必须继续投影到新的匿名类型。它也会让所有这些变量名有点混乱,这就是为什么当我需要执行这样的查询时,我倾向于使用LINQ查询语法而不是lambdas。
只是为了好玩,这里有一个使用.SelectMany()的例子,通过给匿名类型更有意义的名称看起来更好一些,更现实:
public void Get_StarPowerCorporations_PendingShipment_Orders_Shipping_To_NewYork_Or_Chicago()
{
var session = UnitOfWork.Current.GetSession();
var listOfCities = new List<string> { "New York", "Chicago" };
var customerAndOrders = session.Query<Customer>()
.SelectMany( c => c.Orders, ( Customer, Orders ) => new { Customer, Orders } )
.SelectMany( CustomerAndOrders => CustomerAndOrders.Orders.OrderDetails, ( CustomerAndOrders, OrderDetails ) => new { CustomerAndOrders, OrderDetails } )
.Where( x => x.CustomerAndOrders.Customer.CompanyName == "StarPower Corporatation"
&& x.CustomerAndOrders.Orders.Status == "Pending Shipment"
&& listOfCities.Contains( x.OrderDetails.City ) )
.Select( x => x.CustomerAndOrders.Customer )
.Fetch( x => x.Orders )
.ToList();
}
public class Customer
{
public int CustomerId { get; set; }
public string CompanyName { get; set; }
public IList<Address> Addresses { get; set; }
public IList<Order> Orders { get; set; }
}
public class Address
{
public int AddressId { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string Status { get; set; }
public IList<OrderDetail> OrderDetails { get; set; }
}
public class OrderDetail
{
public int OrderDetailId { get; set; }
public string City { get; set; }
}