LINQ加入查询问题

时间:2011-09-28 10:21:00

标签: asp.net vb.net linq

我有这个查询,我尝试将两个表连接在一起,一个包含产品名称和产品编号,并获取产品编号,然后转到另一个查找Art_no的地方,就像产品编号一样。

ProductNamesList = (From ProductSeries In context.Products
                             From ProductRevisions In context.TestResults
                             Where ((ProductSeries.Product = CurrentProduct) And (ProductRevisions.Art_no.Contains(ProductSeries.Product_no)))
                             Order By ProductRevisions.Art_no
                             Select ProductRevisions.Art_no).Distinct.ToList

希望有人可以提供帮助, 谢谢。

2 个答案:

答案 0 :(得分:1)

查看帖子:SQL to LINQ ( Case 7 - Filter data by using IN and NOT IN clause)

您的解决方案分为两个查询,如下所示

//first get the list of product which satisfy your condition

    var ids = (from p in context.Products
              Where p.Product = CurrentProduct
              select p.Product_no).ToList();

//second filter the revision products by using contains

    var myProducts = from p in context.TestResults
                     where ids.Contains(p.Art_no)
                     Order By p.Art_no
                     Select p.Art_no;

答案 1 :(得分:1)

假设有以下类结构:

public class Context
{
    public IEnumerable<Product> Products { get; set; }
    public IEnumerable<TestResult> TestResults { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class TestResult
{
    public int ArtNo { get; set; }
}

上下文的一个例子:

var context = new Context
                {
                    Products = new List<Product>
                                {
                                    new Product {Id = 1, Name = "P1"}, 
                                    new Product {Id = 2, Name = "P2"},
                                },
                    TestResults = new List<TestResult>
                                {
                                    new TestResult {ArtNo = 1},
                                    new TestResult {ArtNo = 2}
                                }
                };
var currentProduct = context.Products.ElementAt(0);

这应该返回您的期望:

var query = from product in context.Products
            from testResult in context.TestResults
            where product.Id == testResult.ArtNo
            && currentProduct == product
            orderby testResult.ArtNo
            select product.Name;

// Returns a list with one item "P1"
var productNames = query.Distinct().ToList();