我有一个客户对象。Customer 对象可能包含多个 Address 对象。
例如,我想在 Customer 对象上设置一个方法GetCity
。
现在,每个 Address 对象都有一个 addressId,所以我试图通过 linq 查询该属性。
下面是我的代码(我已经为这个问题剪掉了它)
客户对象...
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)
在 Customer 对象上运行该方法时,我得到了错误。
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;
}
我知道 Customer 对象中确实包含 Address 对象,但我不确定如何让GetCity
Method 工作。
任何帮助,将不胜感激。如果我错过了任何重要信息,请告诉我。