通过组合两个列表来创建列表

本文关键字:列表 两个 创建 组合 | 更新日期: 2023-09-27 18:36:58

我是.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 语句列出带有国家/地区的客户。但是我很困惑如何创建一个包含客户和国家/地区名称的列表。

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

提前谢谢。

通过组合两个列表来创建列表

与其在

Customer 类中存储国家/地区 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 语句中,联接到国家/地区表并获取国家/地区名称作为结果集的一部分,然后您可以在一次服务器往返中填充客户列表。

您可以添加到您的客户类中

public Country country { get; set; }

如果您确实可以从数据库中获取正确格式的数据,请务必先这样做!数据为此进行了优化。

但是,如果您有两个列表并且需要使用它,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并返回该类的实例。

是的

,您需要创建一个包含每个(客户和国家/地区)的单独属性的类,或者需要创建一个包含其他国家/地区属性的增强型客户类。

我建议看看实体框架。

它是Microsoft的对象关系映射器(ORM),它旨在抽象数据库访问,就像您尝试的那样。