在LINQ

时间:2015-06-17 14:58:07

标签: c# linq linq-to-sql

我有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

表2中的Id1和Id2是对表1中Id的引用

对于每个人(表1中的Id),我想选择Table2中具有最高MatchLevel的行,不包括名为NULL的人。

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

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

LINQ查询如何?如果它不是Lambda表达式,我会很感激。

2 个答案:

答案 0 :(得分:0)

这是动态写的,因为你没有提供数据类,所以请原谅任何错误。我也认为空名也被删除了,所以如果这不正确,请更改查询中的检查:

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()})

答案 1 :(得分:0)

某些地方:

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)
    });