0

I have a query, which will give the result set . based on a condition I want to write the where clause. that means . I have a variable x, if the value of x is "ALL" then I don't want to add this condition at all.if the value is not "ALL" then I need to add a where clause (where st.address==x). how can I add this condition in below query .

var abc=(from st in Context.STopics join ap in Context.ATopic on st.id equals ap.id
where   st.address==x
select new result()
{
name = st.name 
add= ap.add}).ToList();
poc
  • 183
  • 2
  • 3
  • 14

3 Answers3

3

Here is what you're looking for:

var yourQuery = Context.STopics.AsQueryable(); 
var yourParam = "ALL";
if(yourParam != "ALL")
   yourQuery = yourQuery.Where(x => x.IsActive==true && x.StudentID == 123);

var abc = yourQuery.Select(x=> new result()
                               {
                                  name = st.name 
                               }).ToList();

The thing is that with linQ you don't get your data from query right away. So you can construct your actual query this way as you need.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
2

You can make your condition in a way that matches all elements when x = "ALL" and otherwise match your other conditions:

var abc=(from st in Context.STopics 
where  x == "ALL" || (st.IsActive==true && st.StudentID == 123)
select new result()
{
name = st.name }).ToList();
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171
  • 2
    I think I've asked this a few times before, but _please_ add some explanation to your answers instead of dumping "fixed" code. You also don't want this query to be executed on the database, if it can be prevented. It'll become `WHERE 'ALL' = 'ALL'`, which can be done clientside either way. – CodeCaster Mar 22 '16 at 09:16
  • @CodeCaster is it better now? – Ashkan Mobayen Khiabani Mar 22 '16 at 09:19
  • Yes, thank you. It helps later readers see what you did. – CodeCaster Mar 22 '16 at 09:25
0

Something like:

var abc=(from st in Context.STopics 
where  (x!="All" ? (st.IsActive==true && st.StudentID == 123) )
select new result()
{
   name = st.name 
}).ToList();
Eminem
  • 7,206
  • 15
  • 53
  • 95