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

4

3 回答 3

5

DefaultIfEmpty

尝试关注

customerInfo.Telephone = 
    contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone)
      .DefaultIfEmpty(new Contact {Data = ""})
      .First().Data;
于 2013-11-04T22:14:18.117 回答
1

你可以这样做:

customerInfo.Telephone =
  contactData.Where(d => d.ContactTypeId == (int)ContactType.Phone)
    .Select(d => d.Data)
    .FirstOrDefault() ?? string.Empty;
于 2013-11-04T22:11:52.377 回答
0

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

var match = contactData.FirstOrDefault(d => d.ContactTypeId == (int)ContactType.Phone);
customerInfo.Telephone = match == null ? string.Empty : match.Data;
于 2013-11-04T22:10:25.960 回答