如果userid为零,我该如何避免If条件到这种情况?
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();
}
答案 0 :(得分:3)
在linq ||
子句中使用where
。您还可以通过查询logList
一次,然后在其上应用不同的投影来改进:
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();
答案 1 :(得分:1)
像这样修改您的查询
var usernames = (from A in logList where A.Id = UserId || UserId == 0 ...