0

I am facing problem to create Linq query following is example following are some data which is available in Db

data-

7604
76041010
7505
750511

and i have another number like which i need to search in above data like

1) 76041010 this number should take 76041010 code from above data
2) 760458688 this number should take 7604 code from above data
3) 7505110022 this number should take 750511 code from above data ,

I need to retrieve maximum matched number from db, I need query please help me to build linq query.

4
  • 3
    Any effort to show? Commented Nov 2, 2017 at 12:21
  • Are you using EntityFramework? What is the name of your db context? Can you post your models & controllers? Commented Nov 2, 2017 at 12:24
  • yes i am using entity framework, my db context is TradeComplianceContext Commented Nov 2, 2017 at 12:25
  • The return in the third scenario is 7505. Shouldn't it be 750511? Commented Nov 2, 2017 at 12:57

1 Answer 1

1

Not the most elegant solution, but produces the result you're expecting:

var result = data.Select(x => x.ToString())
                 .Where(x => input.ToString().StartsWith(x))
                 .OrderByDescending(x => x.Length)
                 .FirstOrDefault();
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for replay , but it should match 4 digit ,
your Linq query seems if 1st or 2nd digit match then also it return data
@kushalpawar how do you mean? could you give an example when it doesn't produce your expected result?
suppose 76111010 will return 76041010 becoz first 2 digits match with number , but it should return null because 7611 number not available in db , it should check start with 4 digit or greater than 4 digit
@kushalpawar if you search for 76111010, using the data from your question (with the 4 values), this code will return null
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.