我有一個Customer對象。 Customer對象可能包含多個Address對象。如何用linq查詢對象的子對象
我想客戶對象上的方法設置爲GetCity
例如。
現在,每個地址對象具有addressId所以我想通過LINQ查詢性能。
下面是我的代碼(我已經砍了這個問題)
Customer對象...
public class Customer
{
private string _customerNo;
private List<CustomerAddress> _addresses = new List<CustomerAddress>();
//other members immitted from this sample
//constructor code, immitted from this sample
public List<CustomerAddress> Addresses
{
get { return _addresses; }
}
//other properties immitted from this sample
public string GetCity(string id)
{
var city = (from a in _addresses
where a.AddressID == id
select a.City).Single();
return city;
}
}
the Address Object...
public class CustomerAddress
{
private string _addressid;
private string _city;
//other members immitted from this sample
public CustomerAddress(string strAddressID, string strAddressLister, string strAddress1, string strAddress2, string strAddress3, string strCity, string strState, string strPostCode, string strCountry,
bool booDefaultAddress, string strDeliveryAddress, string strInvoiceAddress, string strPayAddress, string strVisitAddress, string strDeliveryTerms, string strShipVia, string strRouteId)
{
_addressid = strAddressID;
_addresslister = strAddressLister;
_address1 = strAddress1;
_address2 = strAddress2;
_address3 = strAddress3;
_city = strCity;
_state = strState;
_postcode = strPostCode;
_country = strCountry;
_defaultaddress = booDefaultAddress;
_deliveryaddress = strDeliveryAddress;
_invoiceaddress = strInvoiceAddress;
_payaddress = strPayAddress;
_visitaddress = strVisitAddress;
_deliveryterms = strDeliveryTerms;
_shipvia = strShipVia;
_routeid = strRouteId;
}
////////////////////////////
//CustomerAddress Properties
////////////////////////////
public string AddressID
{
get { return _addressid; }
}
public string City
{
get { return _city; }
}
//other properties immitted from this sample
}
當我在客戶對象上運行GetCity(id)
方法我得到的錯誤。
System.InvalidOperationException:序列不包含任何元素
我也試過在LINQ查詢下面的代碼,但得到了同樣的結果。
public string GetCity(string id)
{
var city = (from a in this.Addresses
where a.AddressID == id
select a.City).Single();
return city;
}
和...
public string GetCity(string id)
{
var city = (from a in this._addresses
where a.AddressID == id
select a.City).Single();
return city;
}
我知道,客戶對象確實包含在它的地址對象,但我不知道如何讓GetCity
法工作。
任何幫助,將不勝感激。如果我錯過了任何重要信息,請讓我知道。
您可以發佈一個Customer對象,以不會忽略? – tschmit007 2013-03-06 15:07:21