Reputation: 181
I have an Employee table ,let us assume with Columns-- Name, Age,Dept.
I need to do search based on condition like
THIRD: exact match
If First Match is found , then well and good.If no Match then we need to go for Second Option where we need to find result if there is any match between two parameters.
Note: I am looking for a Generic Solution(Imagine I have properties to search)
Example: EMP table
If User is searching "A" ,21 and "CSC" then it is straight forward, I can write the code like
context.Emp.Any(p => p.Name== "A"&& p.Age== 21&& p.Dept== "csc");
If user is Searching like "B" "19 " and "DDD" then i can ignore Dept DDD and return Second row , as there is no Exact Match, then i searching with only two properties Match
Upvotes: 0
Views: 78
Reputation: 4629
You can calculate a score based on the number of matches, order by the score and take the first result. Something like this should work:
var bestMatch = context.Emp.Select(
new {
Score = (c.Age == age ? 1 : 0) + (c.Dept == dept ? 1 : 0) + (c.Name == name ? 1 : 0),
Emp = c
}).OrderByDescending(c => c.Score).FirstOrDefault()?.Emp;
P.S.: You also can order directly by the formula without selecting it into an anonymous object first, but I like the readability of the above approach.
Upvotes: 2