1

我将如何在 LINQ 中表达以下内容?

select * from table_1 t1
join table_2 t2 on t1.col1 = t2.col1 and t1.col2 <= t2.col2

这是我尝试过的,但我没有得到想要的结果。我正在尝试加入 2 个表,但由于table_1数量不大于或等于table_2数量,因为WidgetA 我不希望结果中有任何记录(在 xList 中)。

    List<anObj> table_1 = new List<anObj>();
    table_1.Add(new anObj() { Product = "WidgetA", Quantity = 0 });
    table_1.Add(new anObj() { Product = "WidgetB", Quantity = 3 });

    List<anObj> table_2 = new List<anObj>();
    table_2.Add(new anObj() { Product = "WidgetA", Quantity = 1 });
    table_2.Add(new anObj() { Product = "WidgetB", Quantity = 1 });

    var xList =
    from t1 in table_1
    join t2 in table_2
        on t1.Product equals t2.Product
    where t1.Quantity >= t2.Quantity
    select new
    {
        t1,
        t2
    };

    if (xList.Any())
        Console.WriteLine("Found");
    else
        Console.WriteLine("None"); //I'm looking for this result.           
4

3 回答 3

4
from t1 in t1datatable
join t2 in t2datatable
        on t1.col1 equals t2.col1
where t1.col2 <= t2.col2
select new
{
    t1,
    t2 
};
于 2012-10-11T13:56:15.853 回答
2

最简单的方法是编写以下内容:

var q = from t1 in table_1
        from t2 in table_2.Where(x => t1.col1 == x.col1 && t1.col2 <= x.col2)
        select new { t1, t2 };

(即使看起来是这样,它也不会在数据库中创建交叉连接执行计划)

于 2012-10-11T14:00:11.497 回答
1
var result = from t1 in db.table_1
             from t2 in db.table_2.Where(x => t1.col1 == x.col1)
                                  .Where(x => t1.col2 <= x.col2)
             select new {t1, t2};
于 2012-10-11T14:01:15.700 回答