【问题标题】:Join 2 tables with multiple references in LINQ在 LINQ 中加入 2 个具有多个引用的表
【发布时间】:2015-06-27 18:39:12
【问题描述】:

我有 2 个表,Table1 和 Table2。

**Table1**
Id      Name
------------
14443   Michael
55658   Brian
84321   Lisa
335896  NULL
1035    Maya
5221296 Brenda


**Table2**
Id1     Id2         MatchLevel
--------------------------
14443   5221296     0,5192
14443   84321       0,8647
14443   182347      0,6897
**1035  14443**     0,9999
14443   4572311     0,8569
63547   14443       0,9563
335896  14443       0,9418
14443   5221296     0,6942

**55658 5221296**   0,9928
55658   84321       0,8647
55658   182347      0,6897
1035    55658       0,6796
55658   4572311     0,8569
63547   55658       0,9563
335896  55658       0,9418
55658   5221296     0,6942

Table2中的Id1和Id2是对Table1中Id的引用

对于每个人(表 1 中的 ID),我想选择表 2 中匹配级别最高的行,不包括名称为 NULL 的人。

上面的表格应该返回类似下面的内容:

1035    14443       0,9999 (Michael)
55658   5221296     0,9928 (Brian)

LINQ 查询的外观如何?如果它不是 Lambda 表达式,我将不胜感激。

【问题讨论】:

  • 您的 ORM 映射中是否为该表定义了关系?

标签: c# linq linq-to-sql


【解决方案1】:

在某处:

var query1 = 
    (from t1 in table1s
    join t2 in table2s on t1.Id equals t2.Id1
    where !string.IsNullOrEmpty(t1.Name)
    select new {t1.Name, t2.Id1, t2.Id2, t2.MatchLevel});

var query2 =
    (from t1 in table1s
    join t2 in table2s on t1.Id equals t2.Id2
    where !string.IsNullOrEmpty(t1.Name)
    select new {t1.Name, t2.Id1, t2.Id2, t2.MatchLevel});


var query = query1.Union(query2).GroupBy(x => x.Name)
    .Select(x => new 
    {
        Name = x.Key, 
        MatchLevel = x.Max(y => y.MatchLevel)
    });

【讨论】:

    【解决方案2】:

    这是即时编写的,因为您没有提供数据类,所以请原谅任何错误。我还考虑过空名称也被取出,所以如果这不正确,请更改查询中的检查:

    var result = (from con in Table2
    join name1 in Table1 on con.Id1 equals name1.Id
    join name2 in Table1 on con.Id2 equals name2.Id
    where !string.IsNullOrEmpty(name1.Name) && !string.IsNullOrEmpty(name2.Name)
    group new {con.Id1, con.Id2, con.MatchLevel, name1.Name, name2.Name} by name2 into grp
    select new {res = grp.OrderbyDescending(x=>x.MatchLevel).FirstOrDefault()})
    

    【讨论】:

    • 感谢您的回复。我想你应该在第二次加入时也有 Table1,对吧?无论如何,这不会返回所有条目的列表,而只是返回一个。我需要一个完整的列表,每个名称的最高级别(Table1.Cid)。
    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多