简体   繁体   中英

i am trying to write a search query based upon different keys where keys can be null

i am trying to write search query in linq based upon attributes of an object where object attributes can be null. i want to filter result if my column matches the value of some attribute. ie object.country == "pakistan" then all the records of country pakistan should be displayed and if object.country is NULL then all records should be selected.

var query = from x in db.user_info
        join y in db.user_detail_info on x.Id equals y.Id
        where (key != null && key >= x.country) || (key == null)
        select x;

What you are trying to do is essentially a left join, linq does not support left joins unfortunately. But there is a way around this .

Your linq becomes this...

var q =
    from x in db.user_info
    join y in db.user_detail_info on x.Id equals y.Id 
    where (key == null) || (x.country == key)
    select x;

I believe you want something like this? PS - Unable to test it right now.

string country = null; // set this var to a country name
var peopleList = model.People
    .Join(model.PeopleDetails, 
        p => p.PeopleID, 
        pd => pd.PeopleID,  
        (p, pd) => new { p, pd })
    .Where(resultSet =>  
        string.IsNullOrWhiteSpace(country) 
            ? true 
            : resultSet.pd.CountryName.Equals(country))
    .Select(resultSet => resultSet.p)
    .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM