简体   繁体   中英

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

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

像这样修改您的查询

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM