如何在Select()Lambda Expression中返回一个值

时间:2014-06-24 06:25:29

标签: c# lambda

请参阅以下示例,现在我需要检查UserService.GetByUserID()是否为null,然后返回String.Empty。我怎么能一行呢?

var benefits = customerBenefits.Select(n =>
    new CustomerBenefit(n.BenefitID,
        n.AddedByUserID.HasValue 
            ? UserService.GetByUserID(n.AddedByUserID.Value).DisplayName 
            : n.AddedByAgentID, n.Reason);

4 个答案:

答案 0 :(得分:3)

Call service first then assign result.

var benefits = customerBenefits
                        .Select(n => {
                            var user = serService.GetByUserID(n.AddedByUserID.Value);

                            return new CustomerBenefit(
                                n.BenefitID,                   
                                n.AddedByUserID.HasValue ? (user== null ? String.Empty : ).DisplayName) : n.AddedByAgentID,
                                n.Reason} );

答案 1 :(得分:2)

通过在查询语法中使用let,可以存储子结果:

var benefits = from n in customerBenefits
    let hasuserid = n.AddedByUserID.HasValue
    let user = hasuserid ? UserService.GetByUserID(n.AddedByUserID.Value) : null //the call to GetUserID is stored here
           select
                new CustomerBenefit(
                    n.BenefitID,                   
                    hasuserid 
                         ? (user == null ? string.Empty : user.DisplayName) //the stored sub result is reused
                         : n.AddedByAgentID,
                    n.Reason);

答案 2 :(得分:0)

你可以尝试这样的事情:

var benefits = customerBenefits.Select(n =>
        new CustomerBenefit(
            n.BenefitID,                   
            n.AddedByUserID.HasValue 
                ? (UserService.GetByUserID(n.AddedByUserID.Value) == null 
                    ? String.Empty 
                    : UserService.GetByUserID(n.AddedByUserID.Value).
                        DisplayName) 
            : n.AddedByAgentID,
            n.Reason);

答案 3 :(得分:0)

这是你需要的吗?

var benefits = from n in customerBenefits
    let id = n.AddedByUserID.HasValue
    let user = id ? UserService.GetByUserID(n.AddedByUserID.Value) : null            select
                new CustomerBenefit(
                    n.BenefitID,                   
                    id ? (user == null ? string.Empty : user.DisplayName)
                         : n.AddedByAgentID,
                    n.Reason);