user3128658
user3128658

Reputation: 45

searching firstname and lastname from a field containing fullname in linq c#

In my Person table, I have a field named ps_fullname that contains ..well full name of a person. In my aspx page I have a search box to filter people by name. It works fine as long as I type only ONE name. ( one word). If I type two names ( firstname lastname ) the result is zero.

here is my linq statement

string[] namelist = txtName.text.Split(' ');

DatabaseContext db = new DatabaseContext();

var query = (from person in db.People
     where
     (dhaaira == 0 ? true : (dhaaira == null ? person.ps_default_dhaaira_id == null : person.ps_default_dhaaira_id == dhaaira)) &&
     (atoll == 0 ? true : (atoll == null ? person.PAddress.Island.il_atoll_id == null : person.PAddress.Island.il_atoll_id == atoll)) &&
     (island == 0 ? true : (island == null ? person.PAddress.ad_island_id == null : person.PAddress.ad_island_id == island)) &&
     (address == 0 ? true : (address == null ? person.ps_p_add_id == null : person.ps_p_add_id == address)) &&
     (string.IsNullOrEmpty(nic) ? true : person.ps_nic.Trim().ToLower() == nic.Trim().ToLower()) &&

     (string.IsNullOrEmpty(name) ? true : ( namelist.All( n => person.ps_fullname.ToLower().Contains(n.ToLower()))))
     // orderby orderBy
     orderby person.PAddress.ad_island_id, person.ps_p_add_id, person.ps_fullname
     select person).Skip(startRowIndex).Take(maximumRows).ToList();

What am i doing wrong here? If this is too confusing can you give a simple example where I can filter a string field using multiple words.

Upvotes: 4

Views: 5460

Answers (2)

Emad Mokhtar
Emad Mokhtar

Reputation: 3297

Replace All with Any

namelist.Any( n => person.ps_fullname.ToLower().Contains(n.ToLower()))

I tries it using LinqPad

With Any With All

Upvotes: 1

Liel
Liel

Reputation: 2437

This code works as expected:

     string txtName = "hello wo";
     string[] namelist = txtName.Split(' ');

     string[] db = new string[] { "hello world", "hello dear"};

     List<String> results = db.Where(r => namelist.All( n => r.ToLower().Contains(n.ToLower()))).ToList();

Results will contain one item - "hello world".

So, my guess is that somehow your input is invalid.

Upvotes: 5

Related Questions