1

其他语句在 foreach 循环中无法正常工作?这是我的代码。如果我的代码解释有问题会很好。

protected void getdata_Click(object sender, EventArgs e)
{
    using (var db2 = new cftzClassDataContext())
    {
        var username = (from p in db2.cftzAccounts
                        where p.username.Equals(getdata2.Text)
                        select p);
        foreach (var p in username)
        {
            if (getdata2.Text == p.username)
            {
                displayMSG.Text = "Is this correct ";
                displayData.Text = p.username;
                displayQuestionMark.Text = "?";
            }
            else
            {
                displayMSG.Text = "No User Found.";
            }
        }
    }
}
4

2 回答 2

9

if语句完全是多余的,因为您已经过滤了您的列表以仅包含用户名等于的帐户getData2.Text。因此,您的if测试将始终评估为true.

可以这样改写,效果一样

    using (var db2 = new cftzClassDataContext())
    {
        var username = (from p in db2.cftzAccounts.Take(100)
                        where p.username.Equals(getdata2.Text)
                        select p);

        foreach (var p in username)
        {
            displayMSG.Text = "Is this correct ";
            displayData.Text = p.username;
            displayQuestionMark.Text = "?";
        }
    }

但是,正如 Hans 指出的那样,您的循环也是不必要的,因为所有用户名都是相同的。您的代码可能很简单:

    using (var db2 = new cftzClassDataContext())
    {
        var user = db2.cftzAccounts.
              FirstOrDefault(account => account.username.Equals(getdata2.Text));

        if (user != null)
        {
            displayMSG.Text = "Is this correct ";
            displayData.Text = user.username;
            displayQuestionMark.Text = "?";
        }
        else 
        {
            displayMSG.Text = "No User Found.";
        }
    }
于 2012-07-13T08:04:35.243 回答
0

不确定您尝试实现什么,但看起来您正在尝试查找用户是否在数据库中,如果是,则配置 displayMSG 对象。你不能做类似的事情吗

var user=db2.Single(u=> u.username==getdata2.Text);

如果没有找到用户,Singe 会抛出异常。如果你不这样做,你可以使用 SingleOrDefault() 方法

protected void getdata_Click(object sender, EventArgs e)
{
    using (var db2 = new cftzClassDataContext())
    {
        try
        {
            var user=db2.Single(u=> u.username==getdata2.Text);
            displayMSG.Text = "Is this correct ";
            displayData.Text = user.username;
            displayQuestionMark.Text = "?";
        }
        catch
        {
            displayMSG.Text = "No User Found.";
        }
    }
}
于 2012-07-13T08:13:21.680 回答