2013-11-04 67 views
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。問題是運行相同的查詢兩次。如果我使用變量,我可以擺脫它,但是然後有一個新的變量需要維護。
有沒有辦法讓這段代碼更具可讀性並使其運行得更快而不使用任何其他自定義庫?如何改進這個C#Linq代碼?

回答

5

DefaultIfEmpty

嘗試以下

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

一起使用了這個異常:'System.NotSupportedException:無法創建類型爲'Contact'的常量值。 ' –

+1

這對我有效:'customerInfo.Telephone = contactData.Where(d => d.ContactTypeId ==(int)ContactType.Phone1).Select(d => d .Data) .DefaultIfEmpty(string.Empty) .First();' –

0

我會用一個臨時變量,以防止多個枚舉:

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

你可以這樣做:

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

謝謝。我已經與Tilak的 –