0

I have one code of employee which is A-B-C-D- . Now I want to search all records which are starting with A- till it rich A-B-C-D-. I have tried below code:

var result = db.Employee.Where(x=> x.EmployeeCode.StartsWith("A-B-C-D-"));

Above code gives me only one record. But I want all records which starts with A- then A-B- then A-B-C- and then equals to A-B-C-D-.

Any hint or idea is appreciated.

svick
  • 236,525
  • 50
  • 385
  • 514
Priyank Sheth
  • 2,352
  • 19
  • 32

1 Answers1

1

Have you tried this?

var result = db.Employee
   .Where(x=> x.EmployeeCode.StartsWith("A-")
              || x.EmployeeCode.StartsWith("A-B-")
              || x.EmployeeCode.StartsWith("A-B-C-")
              || x.EmployeeCode.StartsWith("A-B-C-D-");

As you say in the comment that it must be dynamic, then do something like this:

string code = "A-B-C-D-";
var predicates = new List<Expression<Func<Customer,bool>>>();
for (int i = 0; i < code.Length; i++)
{
    if (code[i] == '-')
    {
        var prefix = code.Substring(0, i + 1);
        predicates.Add(x => x.EmployeeCode.StartsWith(prefix));
    }
}
var oredPredicates = ...; // Keep reading!

...

var result = db.Employee.Where(oredPredicate);

Now, you have a lis of predicates, and have to combine them with || (or). To do so it's a bit messy, but there are solutions, for example like in this SO Q&A's:

Once you have all the predicates combined, use it as parameter for your .Where() function.

Unfortunately the most complicated part of combining the expressions is unavoidable, and it's the toughest part to solve this problem, but it works. Please, read the 3 Q&A's, to get insight in what you're doing and get the code that best suits you (beware that using the simple Expression.OrAlso would not directly work, because the x param in each lambda is different for each created expression)

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117
  • Will never work. Operator cannot applied to type string and string. – Priyank Sheth Apr 21 '15 at 08:54
  • You're right. I've change my answer. I didn't have EF code at hand to test it. If you need to do something like the previous version of my answer, use this: `.Where(x => x.EmployeeCode.CompareTo("A-B-C-D-") < 0)`. Is this what you're looking for or you code can greatly change between invocations? – JotaBe Apr 21 '15 at 09:00
  • If it's dynamic, it's harder to implement. I've explained the easiest part of the problem and gave you a reference to the toughest part. I use an extension method for comining predicates, but I don't have the code with me right now. See the other Q&A's. They exaplin and solve this quite complex problem – JotaBe Apr 21 '15 at 09:58