为了账号安全,请及时绑定邮箱和手机立即绑定

where子句仅返回匹配索引数组的产品的子集

where子句仅返回匹配索引数组的产品的子集

C#
慕哥6287543 2021-04-08 13:10:49
我有订购产品的清单。我也有一个索引值列表。我想提取所有索引在索引列表中的产品。现在我正在这样做:var indexes = new List<int> { 1, 2, 5, 7, 10 };var myProducts = orderedProducts.Where((pr, i) => indexes.Any(x => x == i)).ToList();但是,myProducts中只有2个元素:具有索引1和2的产品。它完全错过了5、7和10。这是怎么回事?我该如何解决?注意:orderedProducts.Count始终大于indexes列表的最大值。orderedProducts 由以下内容组成:orderedProducts = productDictionary[fam.Key].ToList().OrderBy(g => g.factor).ToList();其中g.factor,intfam.Key是产品字典的int密钥。我已经检查了myProducts,它确实是List<Product>按升序排序的。prodDictionary是一个Dictionary<int?, List<Product>>。
查看完整描述

2 回答

?
萧十郎

TA贡献1815条经验 获得超13个赞

为什么不只是indexes.Where(i => i < orderedProducts.Count).Select(i => orderedProducts[i]).ToList();


查看完整回答
反对 回复 2021-04-17
?
长风秋雁

TA贡献1757条经验 获得超7个赞

您在测试中错过了一些东西。您说“myProducts.Count总是大于索引列表的最大值”。考虑到您说“ myProducts仅包含2个元素”,这没有任何意义。orderedProducts.Count必须小于6。这就是问题所在。您只需通过比较列表中的索引来提取元素。您可以通过将更多产品添加到列表中来“解决”该问题。


void Main()

{

    var indexes = new List<int> { 1, 2, 5, 7, 10 };


    var orderedProducts = new List<Product>();


    orderedProducts.Add(new Product());

    orderedProducts.Add(new Product());

    orderedProducts.Add(new Product());

    orderedProducts.Add(new Product());

    orderedProducts.Add(new Product());

    //orderedProducts.Add(new Product());//Add this in and you will see a result at index 5

    //orderedProducts.Add(new Product());

    //orderedProducts.Add(new Product());//7

    //orderedProducts.Add(new Product());

    //orderedProducts.Add(new Product());

    //orderedProducts.Add(new Product());//10


    var myProducts = orderedProducts.Where((pr, i) => indexes.Any(x => x == i)).ToList();

}


public class Product

{

}

取消注释产品,您将获得5个预期结果。基于0的数组上的10的索引。


查看完整回答
反对 回复 2021-04-17
  • 2 回答
  • 0 关注
  • 138 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信