繁体   English   中英

将两个列表合并为一个列表

[英]Join two lists into one list

我有两个不同表的两个列表。 列表来自不同的数据库,我需要使用两个列表(表)的结果加入或创建一个新列表,其中列表2的值等于列表1的值

表1 ItemList

订单| 材料|数量|描述| 批量

11| M1       | 1         |Description |x1
22| M3       | 2         |apple       |x2
32| M1       | 10        |banana      |x3
11| M5       | 30        |Description |x4

表2项目ItemSell

订单| 材料|数量|描述| 批量

11| M1       | 12         |Description |x1
22| M3       | 21         |apple       |x2

结果

订单| 材料|库存|描述| 批|

11| M1       | 11         |Description |x1    | 12
22| M3       | 2          |apple       |x2    | 21
32| M1       | 10         |banana      | x3   |0

我的代码是这样的:

result.AddRange(
ItemList.Select(x=>x).Distinct()
.Join(
    ItemSell.Distinct(),
    stock => stock.Material.ToUpper().Trim(),
    sell => sell.Material.ToUpper().Trim(),
    (stock,sell) => newsellItems
    {
        Stock=stock.Quantity,
        sell=sell.Quantity,
        Desc=stock.Desc,
        Batch=stock.Batch,
        Material=stock.Material,
        Order=stock.Order
    }
    ).ToList()
);

有了这段代码,我只会得到这些值

结果

订单| 材料|库存|描述| 批|

11| M1       | 11         |Description |x1    | 12
22| M3       | 2          |apple       |x2    | 21

你所拥有的应该工作。 我在LINQPad中尝试了几乎相同的示例,并得到了您期望的结果:

var stockItems = new[] 
{ 
    new { Order = 11, Material = "M1", Quantity = 1, Desc = "Description", Batch = "x1" }, 
    new { Order = 22, Material = "M3", Quantity = 2, Desc = "apple", Batch = "x2" }, 
    new { Order = 32, Material = "M1", Quantity = 10, Desc = "banana", Batch = "x3" },
    new { Order = 11, Material = "M5", Quantity = 30, Desc = "Description", Batch = "x4" },
};

var sellItems = new[]
{
    new { Order = 11, Material = "M1", Quantity = 12, Desc = "Description", Batch = "x1" }, 
    new { Order = 22, Material = "M3", Quantity = 21, Desc = "apple", Batch = "x2" }
};

stockItems
    .Distinct()
    .Join(
        sellItems.Distinct(), 
        stock => stock.Material.ToUpper().Trim(), 
        sell => sell.Material.ToUpper().Trim(), 
        (stock, sell) => new
        {
            Order = stock.Order,
            Material = stock.Material,
            Stock = stock.Quantity,
            Desc = stock.Desc,
            Batch = stock.Batch,
            Sell = sell.Quantity
        })
    .ToList()
    .Dump();

结果:

Order | Material | Stock | Desc        | Batch | Sell
11    | M1       | 1     | Description | x1    | 12 
22    | M3       | 2     | apple       | x2    | 21 
32    | M1       | 10    | banana      | x3    | 12

您的测试肯定有问题,或者您没有完全粘贴所拥有的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM