0

I'm trying to generate LINQ TO Sql query based on input from user. It's pretty simple to create dynamically LINQ Query with AND predicates:

var query = context.Users;

if (age != null)
{
    query = query.Where(x => x.Age == age);
}

if (name != null)
{
   query = query.Where(x => x.Name == name);
}

So if age and name won't be null after all the query will look like this:

query.Where(x => x.Age == age && x.Name == name);

But how to make it, when instead of AND I want it to be OR? I want the final query to be like this:

query.Where(x => x.Age == age || x.Name == name);
TylerH
  • 20,799
  • 66
  • 75
  • 101
CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36
  • Try to see linqKit – Den Oct 23 '21 at 14:57
  • 4
    Please don't vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](https://creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed, and thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](/help/what-to-do-instead-of-deleting-question). – cigien Oct 27 '21 at 15:26

1 Answers1

0

The syntax you mentioned for OR is correct.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp3
{
class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>
        {
            new Employee { name = "test1", age = 21},
            new Employee { name = "test2", age = 22},
            new Employee { name = "test3", age = 23},
        };

        List<Employee> selectedEmployeesand = employees.Where(x => x.name == "test2" && x.age == 22).ToList();

        Console.WriteLine("using AND");

        foreach (Employee emp in selectedEmployeesand)
        {
            Console.WriteLine(emp.name);
        }

        Console.WriteLine("---------------------------");

        Console.WriteLine("using OR");

        List<Employee> selectedEmployeesor = employees.Where(x => x.name == "test2" || x.age == 21).ToList();

        foreach (Employee emp in selectedEmployeesor)
        {
            Console.WriteLine(emp.name);
        }

        Console.ReadLine();
    }

    public class Employee
    {
        public string name { get; set; }
        public int age { get; set; }
    }
}
}

output:

using AND
test2
---------------------------
using OR
test1
test2
TylerH
  • 20,799
  • 66
  • 75
  • 101
karthik kasubha
  • 392
  • 2
  • 13