2012-06-13 79 views
3

我是.Net的新手。我有两个对象,CustomerCountry在我的项目:通过组合两个列表创建列表

public class Customer 
{ 
    public int CustomerId {get;set;} 
    public string CustomerName {get;set} 
    public String Street {get;set} 
    public String Address {get;set} 
    public int CountryId {get;set} 
    //...o 
} 


public class Country 
{ 
    public int CountryId {get;set;} 
    public String CountryName{get;set} 
} 

我有两个列表,List<Customer>List<Country>.

我使用的是SQL JOIN声明,列出客户的国家。但我很困惑,如何创建一个包含客户和国名的单子列表。

是否有必要为此创建单独的类?

在此先感谢。

回答

7

而不是存储在客户类国家的id,​​只是存储对象本身。也就是说,使它像这样:

public Class Customer 
{ 
public int CustomerId {get;set;} 
public string CustomerName {get;set} 
public String Street {get;set} 
public String Address {get;set} 
public Country Country {get;set} 
//...o 
} 

然后,你必须在你的Customer对象所有需要的信息,而且也没有必要尝试合并列表或类似的东西。

在您的SQL声明中,加入国家/地区表并将国家/地区名称作为结果集的一部分,然后您可以在一次服务器往返中填充客户列表。

0

是的,你需要或者创建一个包含每个(顾客和国家)单独的属性的类,或者,你需要创建一个包含一个额外的国家性质增强的客户类。

1

你可以添加到您的客户类

public Country country { get; set; } 
0

我建议采取看看Entity Framework

这是微软的对象关系映射器(ORM),它是专为抽象就像你正在试图做的数据库访问。

1

如果你能做到在从数据库中正确的格式获得数据,通过各种手段,这样做第一!数据为此进行了优化。

但如果你有两个列表,你需要与工作,LINQ应该有所帮助。你可以做这样的事情:

var query = from customer in customers 
      from country in countries 
      where customer.CountryId == country.CountryId 
      select new 
      { 
       Customer = customer, 
       Country = country 
      }; 

这会给匿名对象的集合与Customer持有物业客户和Country持有物业匹配的国家。

如果你真的需要List<>你总是可以写query.ToList()类型的工作。

如果匿名类型不是你的东西,你可以创建一个新的类,也可以改进Customer类来引用Country并返回一个实例。

相关问题