简体   繁体   English

罗斯文(Northwind)数据库Linq查询

[英]Northwind Database Linq Query

I'm new to Linq and I'm trying to write a query using the northwind database which should return all suppliers who have two or more products in the same category. 我是Linq的新手,正在尝试使用northwind数据库编写查询,该查询应返回所有在同一类别中具有两个或多个产品的所有供应商。

var test1 =
(from p in Products
join pi in Products on p.CategoryID equals pi.CategoryID
join pf in Products on p.SupplierID equals pf.SupplierID
where p.ProductID != pi.ProductID
select new 
{p.ProductName, p.CategoryID, p.SupplierID}).ToList().Distinct();


test1.Dump();

This was my last try that didn't work. 这是我最后的尝试,没有用。 I'm a bit resigned because I've been trying to figure this out for hours and it still won't do what it's supposed to. 我有点辞职,因为我一直试图弄清楚几个小时,但它仍然无法实现预期的效果。 Maybe I'm just getting it completely wrong? 也许我只是完全弄错了?

My approach was that there has to be two or more listings with the same SupplierID and CategoryID but different ProductID, but yet I haven't found a solution. 我的方法是必须有两个或两个以上具有相同SupplierID和CategoryID但具有不同ProductID的列表,但是我还没有找到解决方案。

This is better done using a GroupBy() : 最好使用GroupBy()完成此操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Product> Products = new List<Product>() {
                new Product() { ProductName = "ABC", CategoryID = 1, SupplierID = 1},
                new Product() { ProductName = "DEF", CategoryID = 1, SupplierID = 1},
                new Product() { ProductName = "GHI", CategoryID = 1, SupplierID = 3},
                new Product() { ProductName = "JKL", CategoryID = 1, SupplierID = 3},
                new Product() { ProductName = "MNO", CategoryID = 2, SupplierID = 1},
                new Product() { ProductName = "PQR", CategoryID = 3, SupplierID = 1},
                new Product() { ProductName = "STU", CategoryID = 4, SupplierID = 1},
                new Product() { ProductName = "VWX", CategoryID = 4, SupplierID = 1},
                new Product() { ProductName = "YZ1", CategoryID = 4, SupplierID = 1},
                new Product() { ProductName = "234", CategoryID = 5, SupplierID = 1}
            };



            var test1 = Products.GroupBy(x => new { supplier = x.SupplierID, category = x.CategoryID })
                .Where(x => x.Count() >= 2).Select(y => y.Select(z => new { name = z.ProductName, supplier = y.Key.supplier, category = y.Key.category })).SelectMany(x => x).ToList();

            foreach (var item in test1)
            {
                Console.WriteLine("Name = '{0}', Supplier = '{1}', Category = '{2}'", item.name, item.supplier, item.category);
            }
            Console.ReadLine();
        }

    }
    public class Product
    {
        public string ProductName { get; set; }
        public int CategoryID { get; set; }
        public int SupplierID { get; set; }
    }
}

Your desired outcome is missing, but I can tell you that what you're doing right now is not going to do much good. 您期望的结果丢失了,但是我可以告诉您,您现在正在做的事情不会有多大好处。

Simply put, you're currently asking the database to return all products that match all products that match all products, which basically results in you getting all products, if the database doesn't time out. 简而言之,您当前正在要求数据库返回与所有产品匹配的所有产品,而所有与产品匹配的产品,如果数据库没有超时,则基本上会导致您获得所有产品。 So, we can simplify your query to this: 因此,我们可以将您的查询简化为:

var test1 =
(from p in Products
select new 
{p.ProductName, p.CategoryID, p.SupplierID}).ToList().Distinct();

From this selection, you then want to select an unique lists of product names, category and supplier. 然后,您要从此选择中选择产品名称,类别和供应商的唯一列表。 The main question here is: do you want a unique list of combinations, or does one of the three properties need to be unique? 这里的主要问题是:您想要一个唯一的组合列表,还是三个属性之一需要唯一? Assuming the first, the easiest way to get your result is as such: 假设第一种,获得结果的最简单方法是:

public class ProductResult  : IEquatable<ProductResult> // we have to tell C# compiler how to check if the objects are different from one another
{
   public string Name { get; set; }
   public string Category { get; set; }
   public string Supplier { get; set; }

   public bool Equals(ProductResultother)
            {
                if (other == null)
                    return false;

                return (Category == other.Category) 
                       && Supplier  == other.Supplier)
                       && Name  == other.Name ); // optionally do an .Equals() to make this case-insensitive (check for nulls first if you do this!)
            }
}

Then you can do this: 然后,您可以执行以下操作:

var test1 = (from p in Products
select new ProductResult()
{
   Name = p.ProductName,
   Category = p.CategoryId,
   Supplier = p.SupplierID,
}).Distinct();

You now have a list of all unique product name / category / supplier combinations. 现在,您将获得所有唯一产品名称/类别/供应商组合的列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM