【问题标题】:Can two Lists be joined if types are different like List<T> and List<G>?如果 List<T> 和 List<G> 等类型不同,是否可以连接两个 List?
【发布时间】:2015-09-27 23:53:50
【问题描述】:

我有两个不同的类,如下所示:

public class ProductDto : IDto
    {
        public int Parentproductid { get; set; }
        public string Parentproductnumber { get; set; }
        public int Supplierid { get; set; }
        //More properties
    }

    public class OrderItemsDto : IDto
    {
        public int Poid { get; set; }
        public System.DateTime Createddate { get; set; }
        public int Parentproductid { get; set; }
        public int Variationid { get; set; }
        public System.DateTime Deliverydate { get; set; }
        //More properties
    }

我需要做的基本上是在 parentproductid 上加入 List&lt;OrderItemsDto&gt;List&lt;ProductDto&gt;(就像它们是数据库表一样)并生成另一个列表。

我尝试过使用Union,如下所示:

List<ProductDto> productParents = productManager.getList();
List<OrderItemsDto> orderItemsList = ordermanager.getList();
gvPurchaseOrderItems.DataSource =  orderItemsList.Select(o => o.Parentproductid).Union(productParents.Select(pp => pp.parentproductid));

但这只会给我一个List&lt;int&gt; parentproductids 的结果,在这两个列表中我需要具有两个类的属性(上述情况下为列)的东西。而且我找不到如何使用 Select 扩展方法选择多个属性(我是初学者)

我知道我可以创建一个新类并手动映射属性,但我真的很好奇如何使用 lambda 表达式或 linq 来做到这一点。这可能吗,如果您能给我指明方向,我将不胜感激。谢谢。

【问题讨论】:

    标签: c# linq list generics lambda


    【解决方案1】:

    您可以使用Select 为您的查询创建匿名类型:

    orderItemsList.Select(o => new { o.Parentproductid, o.Variationid, /* etc */ })
    

    所以,在你的情况下:

    gvPurchaseOrderItems.DataSource =  orderItemsList
        .Select(o => new { o.Parentproductid, o.Variationid, /* etc */ })
        .Union(productParents
            .Select(pp => new { pp.Parentproductid, pp.Variationid, /* etc */ }));
    

    【讨论】:

    • 谢谢,我有这样的想法,但我找不到怎么做。
    【解决方案2】:

    由于ProductDtoOrderItemsDto 都实现了IDto 接口,因此您尝试过不需要匿名类型,这应该可以:

    gvPurchaseOrderItems.DataSource =  orderItemsList.Cast<IDto>().Union(productParents);
    

    所有通用属性(即在我假设的接口中定义的)都将存在,以及使用另一种类型转换的特定于类型的属性。

    根据您的评论(以及它是 DTO 的事实,我很傻),您绝对应该选择 Dave Bish 的答案。

    【讨论】:

    • 没有通用属性,接口主要是因为后面有一个通用的存储库。此外,我需要以某种方式指定将在 gridView 上显示的属性。我不想使用 [Browsable(false)] 因为我可能需要在其他页面上显示它们。
    【解决方案3】:

    如果您想将Parentproductid 上的两个列表合并为一个列表,请尝试:

    var result = from pm in productManager
                 join om in ordermanager on pm.Parentproductid equals om.Parentproductid
                 select new { pm.Parentproductid, pm.Parentproductnumber,
                              pm.Supplierid, om.Poid /* more properties */ };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2022-01-17
      • 2017-03-11
      相关资源
      最近更新 更多