通过Linq分组并联接两个表,并嵌套foreach

时间:2018-12-07 05:42:40

标签: c# linq

我有这个LINQ查询:

var Linq6 = from c in northwindEntities.Categories
            join p in northwindEntities.Products on c.CategoryID equals p.CategoryID
            group c by c.CategoryName into Category                                
            select Category;

foreach (var item in Linq6)
{
    Console.WriteLine(item.Key);
    foreach (var i in item)
    {
        Console.WriteLine($" {i.CategoryName}");
    }
}

但是上面的LINQ查询给了我这个输出:

Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
 Beverages
Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
 Condiments
Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
 Confections
Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
 Dairy Products
Grains/Cereals
 Grains/Cereals
 Grains/Cereals
 Grains/Cereals
 Grains/Cereals
 Grains/Cereals
 Grains/Cereals
 Grains/Cereals
Meat/Poultry
 Meat/Poultry
 Meat/Poultry
 Meat/Poultry
 Meat/Poultry
 Meat/Poultry
 Meat/Poultry
Produce
 Produce
 Produce
 Produce
 Produce
 Produce
Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood
 Seafood

实际上,我想要的是第二个foreach循环,用于打印产品名称而不是我找不到的类别名称。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

您需要先分组,然后再加入两个集合,例如

var Linq6 = (from p in northwindEntities.Products
             group p by p.CategoryID into grp
             join c in northwindEntities.Categories on grp.Key equals c.CategoryID
             select new
             {
                 Key = c.CategoryName,
                 Products = grp.ToList()
             }).ToList();


foreach (var item in Linq6)
{
    Console.WriteLine(item.Key);
    foreach (var i in item.Products)
    {
        Console.WriteLine($" {i.ProductName}");
    }
}

输出:

enter image description here

答案 1 :(得分:0)

需要这样做:

for link in soup.findAll('a', attrs={'ng-href': re.compile(r"\.xls")}):
    xls_link = "https://SOMEWEBSITE" + link['ng-href']
    print(xls_link)
    links.append(xls_link)

然后您可以迭代名称和产品