I am lost with the Linq Shorthand IN clause

33 Views Asked by At

I have searched and found lots of almost understandable answers but either I am totally bonkers or they just don't fit in my LINQ Shorthand syntax. I looked at all the "similar duplicate questions" . . . I used The Google too. Maybe I just don't know how to ask the question.

My code to return only 3 cities for now out of a table of Cities. My shorthand works for CityID == 1 but I don't know how to reference the array I inserted with 3 different cities: 1,2,3. It would not scale very nice if I were to use the CityID==1 || CityID==2 || CityID==3 syntax and in the future planned to add 10-100 more cities.

      public IList<Models.Cities> Cities { get;set; }
    
        public async Task OnGetAsync()
        {
            Cities = (IList<Models.Cities>)await _context.tblCities.ToListAsync();
            
            var citylist = new int[] { 1, 2, 4 };

            Cities = Cities.Where(x => x.CityID==1).ToList();
    
        }

BIG EDIT/ANSWER: Svyatoslav Danyliv's solution worked and here is how I use it. I can stack all sorts of calculation or criteria building one piece at a time rather that one huge query that is a "work or doesn't". Easy to take out or add the little pieces I put together. Many times these Lambda expressions take values from what is sent to OnGetAsync().

    public async Task OnGetAsync(string blah, int blahblah, int yadayada) 
{
     var citylist = new int[] { 1, 2, 4 };
     var query = _context.tblCities.AsQueryable();
    
        query = query.Where(c => citylist.Contains(c.CityID));
         
        //SOME CALCULATIONS HERE
        query = query.Where(c => c.xxx == blah);
        
       //SOME CALCULATIONS HERE       
        query = query.Where(c => c.yyyy <= blahblah);
        //ADD MORE  HERE
       query = query.Where(c => c.ooo= yadayada);   
 
        //AND FINALLY OPEN THE RAZOR PAGE
        Cities = await query.ToListAsync();
}

Does this increase the overhead? Not sure, you tell me. But when it comes time to scale I could put all the different calculations and criteria in to one honking huge query. Of course I will probably ask Svyatoslav Danyliv thank you very much!

1

There are 1 best solutions below

1
Svyatoslav Danyliv On

Filtering should be done before materialization using Contains.

public async Task OnGetAsync()
{
    var citylist = new int[] { 1, 2, 4 };
    var query = _context.tblCities.AsQueryable();

    if (citylist.Length > 0) // conditional querying
        query = query.Where(c => citylist.Contains(c.CityID))

    Cities = await query.ToListAsync();
}