我不确定标题是否能很好地解释问题,所以这里是代码。我想返回一个匿名对象来绑定我的网格。在该网格中,我想将用户名更改为全名,但前提是我必须使用全名来匹配用户名。在下面的查询中,我得到了CreatedFullname IF CreatedUsername存在于userModels中。如果它不存在那么我根本没有得到记录。我得知的是获取记录,如果在userModels中可用,则显示UserFullname,如果不是,我想返回x.CreatedUsername。
var inf = (from ev in db.Events
where (ev.StartDate >= beginDate && ev.StartDate <= endDate)
orderby ev.StartDate descending
select new
{
EventID = ev.EventID,
EventTitle = ev.Title,
EventDate = ev.StartDate,
StudentCount = ev.EventStudents.Count(),
CreatedUsername = ev.CreatedUsername
}).AsEnumerable().Select(x => new {EventID = x.EventID,
EventTitle = x.EventTitle,
EventDate = x.EventDate,
StudentCount = x.StudentCount,
CreatedUsername = x.CreatedUsername,
CreatedFullname =
userModels.Where(u => u.Username == x.CreatedUsername).FirstOrDefault().UserFullName
});
userModels是一个自定义对象,具有Username,UserFullname,Department等。它是基于beginDate和endDate在pageload上从ActiveDirectory收集的。
答案 0 :(得分:1)
你可以这样做:
CreatedFullname =
userModels.Where(u => u.Username == x.CreatedUsername)
.Select(x => x.UserFullName)
.FirstOrDefault() ?? x.CreatedUsername
或者这个:
var inf =
(from x in
(from ev in db.Events
where (ev.StartDate >= beginDate && ev.StartDate <= endDate)
orderby ev.StartDate descending
select new
{
EventID = ev.EventID,
EventTitle = ev.Title,
EventDate = ev.StartDate,
StudentCount = ev.EventStudents.Count(),
CreatedUsername = ev.CreatedUsername
})
.AsEnumerable()
let model = userModels.FirstOrDefault(u => u.Username == x.CreatedUsername)
select new
{
EventID = x.EventID,
EventTitle = x.EventTitle,
EventDate = x.EventDate,
StudentCount = x.StudentCount,
CreatedUsername = x.CreatedUsername,
CreatedFullname = (model != null)
? x.modelUserFullName
: x.CreatedUsername
});