Group join Linq C#

  • 本文关键字:Linq join Group c# linq
  • 更新时间 :
  • 英文 :


我正在阅读许多网站,以更好地了解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)怎么办?

有人能分享这方面的想法吗?

这些只是传递给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;
    }
}

相关内容

  • 没有找到相关文章

最新更新