2

我不确定标题是否能很好地解释问题,所以这里是代码。我想返回一个匿名对象来绑定我的网格。在该网格中,我想将用户名更改为全名,但前提是我拥有​​与用户名匹配的全名。在下面的查询中,我得到 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 是一个自定义对象,具有用户名、用户全名、部门等。它是在页面加载时从 ActiveDirectory 收集的,基于 beginDate 和 endDate。

4

1 回答 1

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
     });
于 2013-06-07T00:35:36.227 回答