【问题标题】:Problem merging IEnumerable<T> using Lambda expressions使用 Lambda 表达式合并 IEnumerable<T> 时出现问题
【发布时间】:2011-08-23 16:36:02
【问题描述】:

我有 2 个“产品”类型的 IEnumerables - totalProducts 和 ProductsChosen。顾名思义,totalProducts 保存所有可用的产品,ProductsChosen 保存用户选择的产品。

Product 类具有属性IdnumberIEnumerable&lt;AdditonalOptions&gt; options

我正在尝试像这样合并这两个 IEnumerables

public IEnumerable<Product> MergeProducts(IEnumerable<Product> Products, IEnumerable<Product> ProductsChosen)
{
    return ProductsChosen.Concat(Products.Where(r => !ProductsChosen.Any(x => x.ProductId.Equals(r.ProductId))));
}

我已经使用代码从here合并

此代码仅在我考虑产品 ID 时才能正常工作,但如果产品 ID 相同,我还想将 productsChosenIEnumerable&lt;AdditionalOption&gt; optionstotalProducts 的代码合并。但我不确定如何这样做。

有人可以帮我吗?

谢谢

【问题讨论】:

  • 改用 Union() 方法 - 虽然 concat 是公认的答案,但正如您从投票中看到的那样,Union 是首选
  • 改进标签列表以吸引更多浏览量
  • 我认为这个问题需要澄清。我的解释是,您正在寻找Products 的两个集合的并集,并且在Products 的交集上,您想要AdditionalOptions 的并集。对吗?

标签: c# linq ienumerable linq-to-objects


【解决方案1】:

由于所选产品具有不同的选项,因此它们必须是不同的实例。既然您说全部产品都是可用的,那么我假设所选产品 ID 的集合必须是产品 ID 的子集。

此外,由于所选产品是不同的实例,因此每个总产品可能有零个或多个所选产品,因此我的解决方案也适用于这种情况。如果只有 0 或 1,它同样有效。

此外,由于它们是不同的实例并且options 属性是IEnumerable,因此为合并的产品创建一组新实例以便不改变原始的总产品集。

public IEnumerable<Product> MergeProducts(
    IEnumerable<Product> Products,
    IEnumerable<Product> ProductsChosen)
{
    return
        from p in Products
        join pc in ProductsChosen on p.Id equals pc.Id into pcs
        select new Product()
        {
            Id = p.Id,
            number = p.number,
            options = p.options
                .Concat(
                    from pc2 in pcs
                    from ao in pc2.options
                    select ao).ToArray(),
        };
}

您没有解释number 属性是什么,所以我刚刚对Products 列表中的这个值做了一个简单的赋值,而忽略了ProductsChosen 列表中的这个值。

另外,你没有说AdditionalOptions 需要如何合并。这不是用于枚举的 Merge 方法。您需要使用 ConcatUnion 之类的东西来进行合并。我选择了Concat,但这很容易改变。

这对你有用吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 2017-03-09
    相关资源
    最近更新 更多