How can I create a condition where a sentence using LINQ

I have a scenario where I only need to use the WHERE when necessary, otherwise I just want to run my LINQ query without this WHERE .

For example:

if string name = "";

 var res = (from a in db.person select new() { Name = a.FullName, DOB = a.DOB }).ToList(); 

if string name = "satya";

 var res = (from a in db.person where a.person.contains(name) select new() { Name = a.FullName, DOB = a.DOB }).ToList(); 

I know that for this we must write two queries separately, but without writing separate queries, how can we combine them into one query?

+9
c # linq linq-to-entities entity-framework
source share
3 answers

You can do:

 var res = (from a in db.person where name == "" || a.person.Contains(name) select new { Name = a.FullName, DOB = a.DOB } ).ToList(); 

Alternatively, here, using the free syntax, you can create your request and execute it as soon as you finish:

 var query = db.person.AsQueryable(); if(!String.IsNullOrEmpty(name)) { query = query.Where(a => a.person.Contains(name)); } var result = query.Select(s => new { Name = s.FullName, DOB = s.DOB }) .ToList(); 
+20
source share

The following should work, you can customize it the way you like to achieve the desired result. a.person contains only the condition "empty / zero string" or a name, everything else will lead to zero, which we filter at the end

 db.person.Select(a => { if ( String.IsEmptyOrNull(name) || a.person.contains(name)) return new {Name=a.FullName,DOB=a.DOB}; else return null; } ).Where(x => x != null).ToList() 

Created in a text panel, there may be a slight syntax problem.

+1
source share

I think you can use code snippet 2 to get the same result with code snippet 1, even if the name contains an empty string. Why you should make 2 different codes. Is it due to performance issues?

 var res = (from a in db.person where a.person.contains(name) // if empty, it will return all list, just makes sure it not null before select new(){Name=a.FullName,DOB=a.DOB}).toList(); 

I try this on my sample code and it works great

 static void TestContains() { IList<CustomEntity> _a = new List<CustomEntity>(); IList<CustomEntity> _b = new List<CustomEntity>(); _a.Add(new CustomEntity { ID = 1, Code = "a", Description = "aaa" }); _a.Add(new CustomEntity { ID = 2, Code = "c", Description = "c" }); string name = string.Empty; _b = _a.Where(a => a.Description.Contains(name)).ToList(); foreach (CustomEntity temp in _b) { Console.WriteLine(temp.Description); } } 

It will be the result.

 aaa c 
0
source share

All Articles