Linq类型转换委托为.First方法

时间:2013-08-20 10:56:34

标签: c# .net linq .net-4.0 ienumerable

使用下面的方法我怎么能写出这个没有错误

return _session.Query<Data.Model.User>().Select(_userMapper.CreateUser)
          .AsQueryable();

但写下这个

return _session.Query<Data.Model.User>().Where(x => x.Username == username)
         .First(_userMapper.CreateUser);

产生错误。

public User CreateUser(Data.Model.User modelUser)
{
    return new User{UserId = modelUser.UserId, Username = modelUser.Username,
                    Email = modelUser.Email, Firstname = modelUser.Firstname,
                    Lastname = modelUser.lastname};
}

是否返回集合或单个项目,我希望它由create user方法转换。

2 个答案:

答案 0 :(得分:1)

您需要在Select之前致电First()

return _session.Query<Data.Model.User>()
               .Where(x => x.Username == username)
               .Select(_userMapper.CreateUser)
               .First();

或者:

return _session.Query<Data.Model.User>()
               .Select(_userMapper.CreateUser)
               .First(x => x.Username == username);

答案 1 :(得分:1)

return _userMapper.CreateUser(_session.Query<Data.Model.User>().First(x => x.Username == username));