Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当找不到结果时,linq查询返回什么_Linq_Null_Tolist - Fatal编程技术网

当找不到结果时,linq查询返回什么

当找不到结果时,linq查询返回什么,linq,null,tolist,Linq,Null,Tolist,我正在使用查询查看数据库中是否已经存在用户。如果它找到一个用户,它会将其添加到列表中(而不是数据库),并显示一条消息。如果用户不存在,程序将继续添加该用户 将查询结果添加到列表时,如果结果未找到任何内容,则存在此问题。如果查询未找到任何内容(用户尚不存在),则返回的值不是null或0,因此我不确定如何检查该值 我的代码运行良好,但我的问题是试图找到一种更优雅的方法。我尝试将查询结果添加到列表中。如果是“catch”,则表示用户不存在,需要添加。现在我的代码是: var userIsNe

我正在使用查询查看数据库中是否已经存在用户。如果它找到一个用户,它会将其添加到列表中(而不是数据库),并显示一条消息。如果用户不存在,程序将继续添加该用户

将查询结果添加到列表时,如果结果未找到任何内容,则存在此问题。如果查询未找到任何内容(用户尚不存在),则返回的值不是null或0,因此我不确定如何检查该值

我的代码运行良好,但我的问题是试图找到一种更优雅的方法。我尝试将查询结果添加到列表中。如果是“catch”,则表示用户不存在,需要添加。现在我的代码是:

     var userIsNew =
                        from f in controlEntities.Users
                        where (f.UserId == userIdTextBox.Text)
                        select f;

                    List<Users> temp = new List<Users>(); 

                    try
                    {
                        temp = userIsNew.ToList<Users>();
                    }
                    catch
                    {
                        //do nothing
                    }


                    if (temp.Count > 0)
                    {
                        MessageBox.Show("This UserId already exists in the Database. \nPlease try another UserId.");
                    }
var userIsNew=
来自controlEntities.Users中的f
其中(f.UserId==userIdTextBox.Text)
选择f;
列表温度=新列表();
尝试
{
temp=userIsNew.ToList();
}
抓住
{
//无所事事
}
如果(温度计数>0)
{
MessageBox.Show(“此用户ID已存在于数据库中。\n请尝试其他用户ID。”);
}
谢谢你的帮助

另一种方法是:

        var userIsNew = (from f in controlEntities.Users
                                where (f.UserId == userIdTextBox.Text)
                                select f).FirstOrDefault();


        if (userIsNew != null)
        {
            MessageBox.Show("This UserId already exists in the Database. \nPlease try another UserId.");
        }
        bool userIsNew = controlEntities.Users.
            Count(f => f.UserId == userIdTextBox.Text) == 0;

        if (!userIsNew)
        {
            MessageBox.Show("This UserId already exists in the Database. \nPlease try another UserId.");
        }

它的效率很高,因为数据服务器只返回一个数字而不是结果集。

几乎总是错误的。对不返回匹配项的结果调用
.ToList
,应该可以正常工作。它将只是一个包含0个条目的列表。这是我第一次尝试的。但是,当我试图将一个不匹配的结果添加到任何类型的列表中时,它会抛出一个异常。因此,我的解决方法是使用这个抛出的异常作为执行其余代码的一种方式,当结果为空时会引发什么异常?异常仅表示“处理此请求时发生错误”为空和为空是两件不同的事情,因此我不相信这是正确的答案。我看到一个查询返回一个非null对象,即使该对象内的查询结果表明未找到任何内容。如果未找到任何结果,FirstOrDefault应返回null是否始终确定?你能详细说明它是如何没有0个结果的吗