在Linq Query中需要帮助

时间:2014-06-30 18:32:49

标签: c# linq

我正在使用旧的.net重写一个工具到.net 4.0并使用Linq。我是Linq的新手,在解决以下问题时陷入困境:

我有一个名为UserInfo的表,其中包含所有列。但是,我需要一个特定的数据,需要按照以下方式进行,但在Linq中。有人可以帮我解决Linq查询语法吗?任何帮助都值得赞赏。

非常感谢您对此事的任何帮助。

SELECT DISTINCT a.liProviderKey
FROM         UserInfo a INNER JOIN
            UserInfo b ON a.strBusinessType = b.strBusinessType AND
    (a.strCity = b.strCity AND a.strZip = b.strZip AND a.strState = b.strState AND 
            a.strCompanyName = b.strCompanyName AND (a.strDotNum = b.strDotNum OR
            a.strFedTaxNum = b.strFedTaxNum OR
            a.strPhone = b.strPhone)) OR
            (a.strSSN = b.strSSN AND a.strLastName = b.strLastName AND a.strbusinessType='Consumer')
WHERE     (b.liUserKey = @UserID AND a.fActive=1 AND a.fAuthenticated=1)

1 个答案:

答案 0 :(得分:2)

使用方法语法:

DataContext dc = new DataContext(ConnectionString);
var result = dc.UserInfos.Join(dc.UserInfos, 
                               a => new { strBusinesssType == a.strBusinessType, ..., strSSN = a.strSSN }, 
                               b => new { strBusinesssType == b.strBusinessType, ..., strSSN = b.strSSN }, 
                               (a, b) => new { aTable = a, bTable = b })
                         .Where(o => o.bTable.liUserKey == @UserID && o.aTable.fActive == 1 && o.aTable.fAuthenticated == 1)
                         .Select(o => o.aTable.liProviderKey).Distinct();

使用查询语法:

var query = from a in UserInfos
               join b in UserInfos on new { a.strBusinessType, ..., a.strSSN } equals new { b.strBusinessType, ..., b.strSSN }
               where b.liUserKey == @UserID && a.fActive == 1 && a.fAuthenticated == 1
               select a.liProviderKey;
query = query.Distinct();

如果您想进行复杂的比较,则必须在where子句中进行连接。在这里,您将删除连接并将其替换为第二个(再次,查询语法):

var query = from a in UserInfos
                   from b in UserInfos 
                   where b.liUserKey == @UserID && a.fActive == 1 && a.fAuthenticated == 1 &&
                         ((a.strBusinessType == b.strBusinessType) && ([rest of your conditions]))
                   select a.liProviderKey;
query = query.Distinct();
相关问题