Using Linq (not Lambda), how do I check if a list is empty and if it's not, return results contained in that list. Otherwise, return all results

I have an optional parameter called UserId. If UserId is passed in, I get a list of stores that are related to that User. If UserId is "", I get every store.

public void Example(userId = ""){

   var usersStores = new List<short>();

   if(userId != "")
       userStores = GetStores(userId);

   var query = from t in _dbContext.FakeTable
            where usersStores.Contains(t.storeId)
            select new ExampleObject 
            {
               id = t.storeId,
               text = t.storeId + " (" + t.storeCity + ")"
            };
 }

So I have the

where usersStores.Contains(p.storeId)

Is there a way, in the same query, to do a If usersStore.Count > 0 then userStores.Contain(p.storeId) else Pretend this line doesn’t exist and give me all the results?

Because it does some stuff with query afterwards, I don’t want to change it very much.

>Solution :

You could use where userStores.Count == 0 || usersStores.Contains(t.storeId) to only apply the contains condition if the list is not empty

Leave a Reply