2015-05-08 36 views
0

我正在使用this library以獲得Javascript中的LINQ功能。但是,我無法讓SingleOrDefault()在我的代碼中工作。它返回多個值。JavaScript LINQ:無法獲得SingleOrDefault以返回單個值

這裏是我的(AngularJS)代碼:

customerService.getCustomer(customerId) 
    .then(function (data) { 
     $scope.customer = data.data; 
     var primaryContact = Enumerable.From(data.data.contacts) 
      .SingleOrDefault(function (x) { return x.isPrimaryContact }); 
     if (primaryContact) $scope.customer.address = primaryContact.address.addressLines; 
     $scope.customer.customerType = 'DEFAULT'; 
    }) 
.catch(function (errorData) { alert("There has been an error retrieving the customer") }); 

的的SingleOrDefault()返回即使我知道肯定只有一個滿足條件接觸多個值。

有沒有人使用過這個庫,遇到同樣的問題?以下是正在使用的XML的示例:

<contacts> 
    <notification/> 
    <address> 
     <notification/> 
     <addressId>400059994</addressId> 
     <addressLines>My Address 
     </addressLines> 
     <country>9000</country> 
     <county>East Sussex</county> 
     <postcode>BN12 1PP</postcode> 
     <town>Hove</town> 
    </address> 
    <contactId>400161871</contactId> 
    <emailAddress>[email protected]</emailAddress> 
    <isAccountsContact>false</isAccountsContact> 
    <isAirlineListContact>false</isAirlineListContact> 
    <isDefaultInvoicingContact>false</isDefaultInvoicingContact> 
    <isDeleted>false</isDeleted> 
    <isMarketingRegistered>true</isMarketingRegistered> 
    <isPrimaryBrokerContact>false</isPrimaryBrokerContact> 
    <isPrimaryContact>true</isPrimaryContact> 
    <telephoneNumber>01273 123123</telephoneNumber> 
    <website>www.fromthiscomesthat.co.uk</website> 
    </contacts> 
    <contacts> 
    <notification/> 
    <contactId>400161872</contactId> 
    <customerContactType>15000</customerContactType> 
    <forename>we</forename> 
    <isAccountsContact>false</isAccountsContact> 
    <isAirlineListContact>false</isAirlineListContact> 
    <isDefaultInvoicingContact>false</isDefaultInvoicingContact> 
    <isDeleted>false</isDeleted> 
    <isMarketingRegistered>true</isMarketingRegistered> 
    <isPrimaryBrokerContact>true</isPrimaryBrokerContact> 
    <isPrimaryContact>false</isPrimaryContact> 
    <surname>wew</surname> 
    <title>A Test Contract</title> 
    </contacts> 
+0

你能展示一個簡短但完整的例子來證明這個問題嗎? (作爲源數據的簡單數組就足夠了......) –

+0

上面添加了XML。正如您所看到的,只有其中一個聯繫人將isPrimaryContact設置爲true。我剛剛注意到SingleOrDefault()可能根本不會返回任何結果,而不是多個聯繫人。這個庫沒有太多的文檔... – serlingpa

+1

我提出了一個* short *但是完整的例子 - 爲什麼使用XML而不是像數組這樣比較簡單的數據源?這樣你可以把整個事情放到一個可運行的代碼片段中...... –

回答

0

我找到了解決方案。我改變一個行添加默認值:

SingleOrDefault(null, function (x) { return x.isPrimaryContact }) 

我發現了一些文件here,雖然我覺得這可能是一個更清晰一點。