用内联LINQ表达式替换LINQ方法

时间:2014-01-10 14:37:58

标签: c# linq

我的代码运行正常。

 RequsitionView ConvertMethod(Models.Requisition  input)
 {
    return new RequsitionView(input);
 }

  .... 

model.Requisitions = AppModel.Requisitions.Where(x => x.ClientId == clientId).Select(ConvertMethod).ToList();

但我想简化它并用内联LINQ表达式替换ConvertMethod

我无法弄明白该怎么做。

有任何线索吗?

P.S。我尝试了一些解决方案,但没有快乐。

model.Requisitions = AppModel.Requisitions
                             .Where(x => x.ClientId == clientId)
                             .Select(input => new RequsitionView(input))
                             .ToList();

顺便说一下RequsitionView班级是

public sealed class RequsitionView
    {

        public RequsitionView()
        {

        }

        public RequsitionView(Requisition requisition)
        {
            UID = requisition.UID;
            Id = requisition.Id;
            ExpectedStartTime = requisition.ExpectedStartTime;
            ExpectedEndingTime = requisition.ExpectedEndingTime;
            RealEndingTime = requisition.RealEndingTime;
            ClientId = requisition.ClientId;
            ClientType = requisition.ClientType;
            PatientId = requisition.PatientId;

4 个答案:

答案 0 :(得分:5)

model.Requisitions = AppModel.Requisitions
    .Where(x => x.ClientId == clientId)
    .Select(x => new RequsitionView(x))
    .ToList();

答案 1 :(得分:5)

model.Requisitions = AppModel.Requisitions
                             .Where(x => x.ClientId == clientId)
                             .Select(input => new RequsitionView(input))
                             .ToList();

答案 2 :(得分:2)

您的Select方法是一个预测,因此您需要做的就是将每个项目投影为新的RequisitionView,即

var views = AppModel.Requisitions
    .Where(x => x.ClientId == clientId)
    .Select(x => new RequisitionView(x))
    .ToList()

答案 3 :(得分:-1)

model.Requisitions = AppModel.Requisitions.Where(x => x.ClientId == clientId).Select(o=>new RequsitionView(o) ).ToList();