Linq 'into' keyword confusion

前端 未结 3 1301
走了就别回头了
走了就别回头了 2020-12-13 05:31

I was looking at a co-workers Linq query, shown below (the query executes correctly):

from ea in EquipmentApplication
join erl in EquipmentRoutingLocation on         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 05:38

    To add to what has already been said, I'd like to demonstrate the difference in the object structure produced by into versus without:

    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        select new { Category = c, Products = ps }; 
    

    Creates an object graph:

    Category 1, Products:
      Product 1
      Product 2
    Category 2, Products:
      Product 3
      Product 4
    

    In this case, q only contains 2 items, the two categories.

    Without into, you get a more traditional join that flattens the relationship by creating all possible combinations:

    var q = 
        from c in categories 
        join p in products on c equals p.Category 
        select new { Category = c, Product = p }; 
    
    Category 1, Product 1
    Category 1, Product 2
    Category 2, Product 3
    Category 2, Product 4
    

    Note that now q contains 4 items.

    Update, I think:

    var q = 
        from c in categories 
        join p in products on c equals p.Category into ps 
        select new { Category = c, Products = ps.Select(x=> x.Id) }; 
    

提交回复
热议问题