为什么我的linq序列中会得到空值? [英] Why do I get null values in my linq sequence?

查看:112
本文介绍了为什么我的linq序列中会得到空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的程序员再次问好,



我因为我的linq查询问题而苦苦挣扎了几天。





当我正在调试并且用鼠标悬停在教育上时,值(这是一个字符串)是空的。最糟糕的是当我更换时它与我的数据库中的字符串,它完美的工作。我没有发布绑定部分,因为它的工作时,我用正常的字符串替换教育,但如果它有任何相关性,请告诉我,以便我可以发布它。空字符串的问题是什么?我搜索了一个尝试了很多方法的答案,但都失败了。我正在使用linq和sql.Thank你!



我尝试过:



这是我目前的代码:

ViewModel:

Hello again dear programmers,

I'm struggling for a couple of days with a problem regarding my linq query.


When I'm debugging and I hover with my mouse over education,the value(which is a string) is empty.The worst part is that when I'm replacing it with a string from my database,it works perfectly.I did't post the binding part since it works when i replace"education" with a normal string,but if it has any relevance,please tell me so that I can post it.What would be the issue for the empty string?I searched for an answer an tried many approaches,but all of them failed.I'm using linq with sql.Thank you!

What I have tried:

This is my current code:
ViewModel:

private String education;
      public String Education
      {
          get { return education; }
          set
          {
              if (education != value)
              {
                  education = value;
                  NotifyOnPropertyChange("Education");
              }
          }
      }

这是我要将值传递给的字符串。



这是我的方法:

This is the string that i want to pass the value to.

This is my method:

public List<Cours> CreateCrazy()
     {
         using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
         {
             if(education==null)
             {
                 education = "";
             }
             try
             {

                 var query = (from data in db.Courses where data.education==education select new { CourseName = data.courseName }).ToList().Select(c => new Cours { courseName = c.CourseName }).ToList();
                 return query.ToList();

             }

             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
         }
         return null;
     }

education是空值。

"education" is the null value.

推荐答案

正如Maciej在他的评论中指出的那样,问题很可能如下:

As Maciej pointed out in his comment, your issue is most likely the following:
private String education; //implied default of null
public String Education
{
    get { return education; } //simply a return
}

public List<Cours> CreateCrazy()
{
    using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
    {
        //Education/education will always be null if it hasn't been set yet.
        if(education==null)
        {
            education = "";
        }
    }
}



我最好的猜测是它不起作用,因为你通常会测试它 education 未设置,因此 null 默认为 CreateCrazy 里面。使用硬编码字符串替换 education 时,它可以正常工作,因为LINQ查询在技术上没有任何问题。这很可能是你绑定中的一个问题。



其他想法:

属性:如果需要,始终在属性或字段上设置默认值,而不是在方法内部进行默认设置。这使变量状态保持一致。现在编写代码有两种默认状态,具体取决于是否已调用 CreateCrazy - null



功能:如果可能的话,尝试维持单一出口是一种好习惯 - 功能点。它使代码更易于阅读,遵循,从而维护。在我看来,这与另一个好的做法联系在一起 - 消除尽可能多的 null 依赖。如果你调用一个查询并返回结果数组的函数,你不希望没有结果只是一个空数组吗?这也允许简化消费代码。而不是必须 null 检查你可以简单地迭代。如果没有结果,循环将立即退出。



LINQ:太多 ToList 电话。 ToList 强制评估LINQ表达式,所以永远不要 ToList 查询结果,除非用它完成。可以从查询中删除这两个调用,并在返回值上保留 ToList 。此外,查询的第二部分也不是必需的。您将 courseName 捕获到匿名对象中,然后将该数据传输到另一个select语句中的类型化对象中。第一次输入。



修改建议:


My best guess is that it doesn't work because however you are normally testing it education isn't being set so it is null which gets defaulted to "" inside CreateCrazy. When you replace education with a hard-coded string it works because there's nothing technically wrong with the LINQ query. It's most likely a problem in your binding.

Additional Thoughts:
Properties: Always set the default on a property or field if needed instead of defaulting inside a method. This keeps variable state consistent. As the code is written now there are two default states depending on whether CreateCrazy has been called - null and "".

Functions: If possible it's good practice to try to maintain a single exit-point for functions. It makes the code easier to read, follow, and therefore maintain. This ties into another good practice in my opinion - eliminate as much null reliance as possible. If you call a function that queries and returns a results array, wouldn't you expect "no results" to just be an empty array? This also allows the consuming code to be simplified. Instead of having to null check you can simply iterate. If there are no results the loop will just exit immediately.

LINQ: Way too many ToList calls. ToList forces an evaluation of the LINQ expression so never ToList a query for results unless finished with it. Both calls could be removed from the query and just leave the ToList on the return value. Also the second part of the query isn't necessary. You're capturing courseName into an anonymous object and then transferring that data into a typed object in another select statement. Type it the first time.

Modified with suggestions:

private String education = string.Empty;
public String Education
{
    get { return education; }
    set
    {
        if (education != value)
        {
            education = value;
            NotifyOnPropertyChange("Education");
        }
    }
}

public List<Course> CreateCrazy()
{
    List<Course> courseResult = new List<Course>();
    using (DatabaseStudentsEntities1 db = new DatabaseStudentsEntities1())
    {
        try
        {
            var query = from data in db.Courses
                        where data.education == Education
                        select new Course { 
                            CourseName = data.courseName 
                        };
            courseResult.AddRange(query);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
    return courseResult;
}


这篇关于为什么我的linq序列中会得到空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆