Home > Back-end >  how use like in sql on linq c#
how use like in sql on linq c#

Time:07-20

this not work

string[] DATE_Group = { "2020", "2021" }; //changing values
var query = _context.c10
            .Where(u => DATE_Group.Any(s => u.ON_DATE.Contains(s)))
            .ToList()
            .Select(u => new
            {
                User_NumberID = u.User_NumberID.ToString(),
            }).ToList();

I use this u.ON_DATE.Contains("2020") and work but not list or array only one value

in sql SELECT * from C10 where ON_DATE like ' 20%' or ON_DATE like ' 21%' and in ON_DATE column content like this 1-3-2023 1-1-2021 5-1-2020

this error when used enter image description here

CodePudding user response:

Use this below code for your linq where statement.

var myVar=context.Students.where(x=>x.Name.Contains("John")).SingleOrDefault();

CodePudding user response:

I think this is a better way to get the data:

var from = new DateTime(2020,1,1);
var to   = new DateTime(2022,1,1);
var query = _context.c10
            .Where(u => u.ON_DATE > from && u.ON_DATE < to )
            ...

CodePudding user response:

EF Core cannot use Any with local collections (with small excpetion), only Contains is supported.

I would suggest to use function FilterByItems. And use in query:


string[] DATE_Group = { "2020", "2021" }; //changing values

var query = _context.c10
    .FilterByItems(DATE_Group, (u, s) => u.ON_DATE.Contains(s), true)
    .Select(u => new
    {
        User_NumberID = u.User_NumberID.ToString()
    })
    .ToList();
  • Related