Linq迭代一个集合并将另一个集合添加到其成员中

本文关键字:集合 添加 另一个 成员 合并 Linq 一个 迭代 | 更新日期: 2023-09-27 18:00:41

我遇到一种情况,需要遍历一个集合,并使用Linq将另一个集合添加到其成员中。

例如,我有这个类

public class Product
{
    public string Car { get; set; }
    public IEnumerable<Part> Part { get; set; }
}

该类将在类似的集合中

IEnumerable<Product> ProductList

如何使用带Linq 的GetPartData()为每个Product填充Part-属性

private IEnumerable<IEnumerable<Part>> GetPartData()
{
    return new List<List<Part>>() { 
        new List<Part>{
            new Part(){PartType="11",PartValue=1},
            new Part(){PartType="12",PartValue=2}
        },
        new List<Part>{
            new Part(){PartType="21",PartValue=1},
            new Part(){PartType="22",PartValue=2}
        }
    };
}

所以最终,我的ProductList[0].Part应该等于GetPartData()[0]

Linq迭代一个集合并将另一个集合添加到其成员中

如果两个序列都应该通过索引链接,则可以使用Enumerable.Zip:

ProductList = ProductList.Zip(GetPartData()
    , (product, part) => new Product
    {
        Car = product.Car,
        Part = part
    })
.ToList();

基本上,您需要一次枚举两个IEnumerable来匹配两者中的项。CCD_ 8和CCD_。

// The two IEnumerable
var products = ProductList;
var parts = GetPartData();
foreach((product, part) in (products, parts))  // will not work :(
{
    product.Part = part;
}

解决方案以前也有过争论。

Zip方法可以做到。

// The two IEnumerable
var products = ProductList;
var parts = GetPartData();
products.Zip(parts, (product, part) => product.Part = part).ToList();

ToList()非常重要,用于强制执行。

如果你对lambda不满意,你可以这样做:

// The two IEnumerable
var products = ProductList;
var parts = GetPartData();
products.Zip(parts, ProductPartAssociation).ToList();
...
Product ProductPartAssociation(Product product, IEnumerable<Part> part)
{
   product.Part = part;
   return product;      // Actually not used.
}

Zip的结果是ProductPartAssociation函数返回的IEnumerable。您并不关心它,因为您所需要的只是确保ProductPartAssociation被执行。