我正在阅读很多网站,以便更好地了解Linq -Group Join。
var customers = new Customer[]
{
new Customer{Code = 5, Name = "Sam"},
new Customer{Code = 6, Name = "Dave"},
new Customer{Code = 7, Name = "Julia"},
new Customer{Code = 8, Name = "Sue"}
};
// Example orders.
var orders = new Order[]
{
new Order{KeyCode = 5, Product = "Book"},
new Order{KeyCode = 6, Product = "Game"},
new Order{KeyCode = 7, Product = "Computer"},
new Order{KeyCode = 7, Product = "Mouse"},
new Order{KeyCode = 8, Product = "Shirt"},
new Order{KeyCode = 5, Product = "Underwear"}
};
var query = customers.GroupJoin(orders,
c => c.Code,
o => o.KeyCode,
(c, result) => new Result(c.Name, result));//why mention c here??
// Enumerate results.
foreach (var result in query)
{
Console.WriteLine("{0} bought...", result.Name);
foreach (var item in result.Collection)
{
Console.WriteLine(item.Product);
}
}
我无法理解它为什么给出(c,结果)?如果写成(c,o)怎么办?
有人可以就此分享想法吗?
答案 0 :(得分:2)
这些只是传递给Func
的参数的名称。如果能让代码更清晰,您可以使用任何您想要的名称,即:
var query = customers.GroupJoin(orders,
c => c.Code,
o => o.KeyCode,
(something1, something2) => new Result(something1.Name, something2));
因为它只会将前两个Func中的参数传递给Func<TOuter, IEnumerable<TInner>, TResult>
的最后一个,所以在这种情况下Func<Customer, IEnumerable<Order>, Result>
。
与这种情况相同:
public Result DoStuff(Order nameMeAnyWayYouWant, Customer meToo)
{
//do stuff here
}
来自问题的代码来自:http://www.dotnetperls.com/groupjoin
我正在添加作者跳过的模型类,如果有人想详细说明,以及dotnetperls.com发生故障:
class Customer
{
public int Code { get; set; }
public string Name { get; set; }
}
class Order
{
public int KeyCode { get; set; }
public string Product { get; set; }
}
class Result
{
public string Name { get; set; }
public IEnumerable<Order> Collection { get; set; }
public Result(string name, IEnumerable<Order> collection)
{
this.Name = name;
his.Collection = collection;
}
}