包含在Linq查询中,并检查未null[英] Contains in LINQ query and Check for Not null

本文是小编为大家收集整理的关于包含在Linq查询中,并检查未null的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个LINQ查询.因为我正在使用包含包含的列表来过滤一些记录.查询需要在列表值中的任何一个(100或110或120)中查找未null的值.

列表值

List splitted = {"100", "110", "120"}

查询

model = (from line in db.Bibs
         where line.TNo == "245" 
           && (line.NrmVal.StartsWith(Val) || line.NrmVal.Contains(" " + Val))
         select new MyModel
         {
          Author = (from a in db.Bibs 
          where a.BId == line.Bid
            &&  splitted.Contains(a.TNo) 
            &&  a.NrmVal != null 
          select a.NrmVal).FirstOrDefault()
         }).ToList();

为提供解决方案提供任何帮助.

谢谢

推荐答案

尝试此lambda等效

var query = db.Bibs.Where(x => x.TNo == "245");
query = query.Where(x => x.NrmVal.StartsWith(Val) || x.NrmVal.Contains(" " + Val));
query = query.Select(x => new {
            Author = db.Bibs.Where(a => a.BId == x.BId && a.NrmVal != null && splitted.Contains(a.TNo)).FirstOrDefault()
        });

如果您仍然遇到相同的问题,那么我会评论每个部分,直到您发现哪个部分不起作用.我优化了Author查询以在查找列表之前先检查null.

另外,它使代码更容易管理和可辩论.

本文地址:https://www.itbaoku.cn/post/1556857.html

问题描述

I have a Linq Query. In that I am using a list with contains to filter some records. The query needs to look for the values that is not null in any one of the list values (100 or 110 or 120).

List values

List splitted = {"100", "110", "120"}

Query

model = (from line in db.Bibs
         where line.TNo == "245" 
           && (line.NrmVal.StartsWith(Val) || line.NrmVal.Contains(" " + Val))
         select new MyModel
         {
          Author = (from a in db.Bibs 
          where a.BId == line.Bid
            &&  splitted.Contains(a.TNo) 
            &&  a.NrmVal != null 
          select a.NrmVal).FirstOrDefault()
         }).ToList();

Any help in providing the solution is appreciated.

Thanks

推荐答案

Try this Lambda equivalent

var query = db.Bibs.Where(x => x.TNo == "245");
query = query.Where(x => x.NrmVal.StartsWith(Val) || x.NrmVal.Contains(" " + Val));
query = query.Select(x => new {
            Author = db.Bibs.Where(a => a.BId == x.BId && a.NrmVal != null && splitted.Contains(a.TNo)).FirstOrDefault()
        });

If you still get the same problem then I would comment out each section until you find which section doesn't work. I optimized the Author query to check for null first before looking up the list.

Also, it makes the code a bit easier to manage and arguable more readable.