如何在Select() Lambda表达式中返回值?

本文关键字:表达式 返回值 Lambda Select | 更新日期: 2023-09-27 18:10:05

看下面的例子,现在我需要检查UserService.GetByUserID()是否为空,然后返回String.Empty。我怎么还能在一行中完成呢?

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

如何在Select() Lambda表达式中返回值?

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} );

通过使用let - in查询语法,您可以存储子结果:

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);

你可以试试这样做:

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);

这是你需要的吗?

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);