sajiii
sajiii

Reputation: 172

How to use if else in linq

i have a table in which i have record of users.table have field lastLoginMonth and LastLoginYear ...i want to fetch that user who have login time more than 5 month ..but here i found two case .. 1)current year and lastLoginYear same 2)current year and lastLoginYear different to handle this i have to use different conditions but i don't know how to handle this in query.....

var year = db.UserManagers.ToList();

foreach (var y in year)
{
    if (y.LastLoginYear == mydate.Year)
    {
        var modell   = (from ummm in db.UserManagers
                        where ((mydate.Month - ummm.LastLoginMonth) >5 
                            && ummm.LoginWarning==false)
                        select ummm).ToList();
                    return View(modell);

     }

     var model = (from ummm in db.UserManagers
                  where (((12 - y.LastLoginMonth) + mydate.Month) >5 
                  && ummm.LoginWarning == false)
                  select ummm).ToList();
     return View(model);
}

how i can organize this query in a simple way ...

Upvotes: 3

Views: 222

Answers (2)

Kudlaty 01
Kudlaty 01

Reputation: 21

First approach that came to my mind could be with simple inline if:

var year = db.UserManagers.ToList();

        foreach (var y in year)
        {
             var model   = (from ummm in db.UserManagers
                              where (((y.LastLoginYear == mydate.Year)?(mydate.Month - ummm.LastLoginMonth):((12 - y.LastLoginMonth) + mydate.Month)) >5 && ummm.LoginWarning==false)
                              select ummm).ToList();
                return View(model);

            }
}

I assume that you realize that a return inside a foreach loop would make it execute only once and then return the result?

Upvotes: 1

Ivan Yurchenko
Ivan Yurchenko

Reputation: 3871

Use ternary operator:

 var modell   = (from ummm in db.UserManagers
                 where (((y.LastLoginYear == mydate.Year)
                         ? ((mydate.Month - ummm.LastLoginMonth) >5) 
                         : ((12 - y.LastLoginMonth) + mydate.Month) >5)
                       && ummm.LoginWarning==false)
                 select ummm).ToList();

Take a look at this example to understand what does this mean like:

var list = new List<string> { "1", "abc", "5"};
var sel = (from s in list where ((s.Length > 1) ? true : false) select s);

As you can see, we take each string s stored in the list and apply to it the next filter: If it’s Length more then 1, we take it (as it will be where true), otherwise, we don’t take it. Thus we will take only those strings that have Length more then 1.

Also pay attention that you make return inside the foreach loop. That means that the foreach will iterate only 1 time and then will exit on the return you wrote. So you might expect this code to make something different from what you have written.

Upvotes: 5

Related Questions