【问题标题】:join two different list by id into one list按 id 将两个不同的列表加入一个列表
【发布时间】:2015-09-09 04:44:28
【问题描述】:

我有两个不同对象的两个不同列表。然后我得到了一个包含两个对象属性的视图模型列表,我希望它们加入到该列表中。

    //Product
    public string id { get; set; }
    public string unitMeasurement { get; set; }
    public Nullable<int> minOrderQty { get; set; }
    public Nullable<int> packSize { get; set; }
    public string leadTime { get; set; }
    public Nullable<int> generalAccessoryCategoryId { get; set; }
    public string Company { get; set; }
    public Nullable<decimal> Weight { get; set; }
    public Nullable<int> ProductType { get; set; }

    //ProductDescription
    public string id { get; set; }
    public string language { get; set; }
    public string shortDescription { get; set; }
    public string detailDescription { get; set; }
    public string Name { get; set; }
    public Nullable<int> Rank { get; set; }
    public Nullable<System.DateTime> StartDate { get; set; }
    public Nullable<System.DateTime> EndDate { get; set; }


     public class ProductResponse
{

    public string id { get; set; }

    //Product
    public string unitMeasurement { get; set; }
    public Nullable<int> minOrderQty { get; set; }
    public Nullable<int> packSize { get; set; }
    public string leadTime { get; set; }
    public Nullable<int> generalAccessoryCategoryId { get; set; }
    public string Company { get; set; }
    public Nullable<decimal> Weight { get; set; }
    public Nullable<int> ProductType { get; set; }

    //ProductDescription

    public string language { get; set; }
    public string shortDescription { get; set; }
    public string detailDescription { get; set; }
    public string Name { get; set; }
    public Nullable<int> Rank { get; set; }
    public Nullable<System.DateTime> StartDate { get; set; }
    public Nullable<System.DateTime> EndDate { get; set; }
}

所以我只想将产品列表和产品描述列表加入到产品响应列表中。我怎样才能做到这一点? product 和 productdescription 的 id 相同,所以我想加入它们。

【问题讨论】:

    标签: c# list join merge automapper


    【解决方案1】:

    加入他们的 id 然后拨打ToList:

    var productResponses = from p in products 
                           join pd in productDescriptions
                           on p.id equals pd.id
                           select new ProductResponse
                           { 
                              id = p.id,
                              language = pd.language,
                              // ...
                           }
    var list = productResponses.ToList();
    

    【讨论】:

    • 我可以用 lambda 做吗?
    • 当然可以,但是我从不使用方法语法来加入,因为它太丑了。我永远不会记得Enumerable.Join的参数。这并没有降低效率。
    • 我需要任何特殊的使用参考吗?因为它无法解析加入
    • 我的错!我有任务而不是对象:) 所以它可以工作:)
    猜你喜欢
    • 2012-05-29
    • 2022-12-24
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多