0

How can I avoid If condition to this situation if userid is zero?

if (Userid == 0)
{
    var logList = service.GetLogDetails();
    var usernames = (from A in logList orderby A.FirstName select new { Name = A.FirstName + " " + A.SurName, ID = A.Id }).Distinct();
    var loginDate = (from A in logList select A.LogInTime.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();
    var logOutDate = (from A in logList select (A.LogOutTime ?? "Unknown").ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();
}
else
{
    var logList = service.GetLogDetails();
    var usernames = (from A in logList where A.Id == Userid orderby A.FirstName select new { Name = A.FirstName + " " + A.SurName, ID = A.Id }).Distinct();
    var loginDate = (from A in logList where A.Id == Userid select A.LogInTime.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();
    var logOutDate = (from A in logList where A.Id == Userid select (A.LogOutTime ?? "Unknown").ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();
}
1
  • 3
    where A.Id == Userid || Userid == 0 Commented Nov 12, 2016 at 17:54

2 Answers 2

3

Use an || in you linq where clause. Also you can improve by querying the logList once and then applying the different projections on it:

var logList = service.GetLogDetails()
                     .Where(item => Userid == 0 || item.Id = Userid)
                     .ToList();

var usernames = (from A in logList 
                 orderby A.FirstName 
                 select new { Name = $"{A.FirstName} {A.SurName}", ID = A.Id }).Distinct();

var loginDate = (from A in logList 
                 select A.LogInTime.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();

var logOutDate = (from A in logList 
                  select (A.LogOutTime ?? "Unknown").ToString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)).Distinct();
Sign up to request clarification or add additional context in comments.

2 Comments

I have written like this as you say var logList = service.GetLogDetails().Where(item => item.Id == Userid || Userid == 0).ToList(); Now its working. Thanks
@AbhilashJA If his answer helped you, mark it as correct.
1

Modify your queries like this

var usernames = (from A in logList where A.Id = UserId || UserId == 0 ...

1 Comment

Though correct this is like an answer posted 4 minutes ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.