【问题标题】:How to improve this C# Linq code?如何改进这个 C# Linq 代码?
【发布时间】:2013-11-04 22:07:25
【问题描述】:
customerInfo.Telephone = contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone).FirstOrDefault() != null 
                    ? contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone).FirstOrDefault().Data 
                    : string.Empty;

contactData 是 IEnumerator。问题在于两次运行相同的查询。如果我使用变量,我可以摆脱它,但是需要维护一个新变量。
有没有办法在不使用任何其他自定义库的情况下使此代码更具可读性并使其运行得更快?

【问题讨论】:

    标签: .net performance asp.net-mvc-3 linq c#-4.0


    【解决方案1】:

    DefaultIfEmpty

    尝试关注

    customerInfo.Telephone = 
        contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone)
          .DefaultIfEmpty(new Contact {Data = ""})
          .First().Data;
    

    【讨论】:

    • 遇到这个异常:System.NotSupportedException: Unable to create a constant value of type 'Contact'. Only primitive types or enumeration types are supported in this context.
    • 这对我有用:customerInfo.Telephone = contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone1).Select(d=>d.Data) .DefaultIfEmpty(string.Empty) .First();
    【解决方案2】:

    你可以这样做:

    customerInfo.Telephone =
      contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone)
        .Select(d => d.Data)
        .FirstOrDefault() ?? string.Empty;
    

    【讨论】:

    • 谢谢。我已将您与 Tilak 结合使用
    【解决方案3】:

    我会使用一个临时变量来防止多次枚举:

    var match = contactData.FirstOrDefault(d => d.ContactTypeId == (int)ContactType.Phone);
    customerInfo.Telephone = match == null ? string.Empty : match.Data;
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2012-02-11
      • 2017-11-17
      相关资源
      最近更新 更多