DonMax
DonMax

Reputation: 960

Contains in LINQ query and Check for Not null

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

Upvotes: 1

Views: 15763

Answers (1)

James
James

Reputation: 82096

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.

Upvotes: 1

Related Questions