Abhilash JA Abhilash JA - 22 days ago 5
C# Question

C# - if condition in Linq select query with where clause

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();
}

Answer

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();
Comments