使用Linq的情况

问题描述 投票:0回答:2

我在数据库中有一个表格

Code            No                 Email            Pwd
-----------------------------------------------------------    
ABCDEFG         1             [email protected]          1
EYETW           2             [email protected]          2
WDHH0           3                  NULL             NULL
DZDX220         4                  NULL             NULL
AL7F0MI         5                  NULL             NULL
Q5D6M4R         6                  NULL             NULL

现在,在这个表中我必须检查用户使用的email是否已经存在然后我想要检索该行,如果电子邮件不存在那么我必须检查Pwd是否已被使用并检索行数据。

我试过这个

var data = (from table in ds.Tables[0].AsEnumerable()
            where table.Field<Int16>("Pwd") == Convert.ToInt16(pwd) || table.Field<string>("Email") != email
            select new {emailAddress = table.Field<string>("email") , passsword = table.Field<Int16>("Pwd") }).FirstOrDefault();

但它没有回复正确的答案。

测试用例:

如果我通过[email protected]和2,那么我必须检索`[email protected] 1。

如果我通过[email protected]和1然后我想要检索[email protected] 2 or null

对不起,伙计们,如果其中任何一个存在,我想要检索这些值,但不是空值

c# linq linq-to-sql
2个回答
0
投票

您需要更新Where()。应该是这样的:

var data = (from table in ds.Tables[0].AsEnumerable()
            where (table.Field<string>("Email") == email) //email exists
            || (table.Field<string>("Email") != email && table.Field<Int16>("Pwd") == Convert.ToInt16(pwd)) //email doesn't exist, but password does
            select new {emailAddress = table.Field<string>("email") , passsword = table.Field<Int16>("Pwd") }).FirstOrDefault();

0
投票

正如Yacoub在评论中指出的那样,问题是table.Field<string>("Email") == email它应该是== email

var matchingrow = ds.Tables[0].AsEnumerable()
                              .FirstOrDefault(table=> table.Field<Int16>("Pwd") == Convert.ToInt16(pwd) 
                                                   || table.Field<string>("Email") == email);

if(matchingrow != null)
{
    // matching email/pwd. logic goes here

    // matchingrow.Field<string>("Email");
}
© www.soinside.com 2019 - 2024. All rights reserved.