Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading