猿问

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

我有订购产品的清单。我也有一个索引值列表。我想提取所有索引在索引列表中的产品。现在我正在这样做:


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>>。


慕哥6287543
浏览 139回答 2
2回答

萧十郎

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

长风秋雁

您在测试中错过了一些东西。您说“myProducts.Count总是大于索引列表的最大值”。考虑到您说“ myProducts仅包含2个元素”,这没有任何意义。orderedProducts.Count必须小于6。这就是问题所在。您只需通过比较列表中的索引来提取元素。您可以通过将更多产品添加到列表中来“解决”该问题。void Main(){&nbsp; &nbsp; var indexes = new List<int> { 1, 2, 5, 7, 10 };&nbsp; &nbsp; var orderedProducts = new List<Product>();&nbsp; &nbsp; orderedProducts.Add(new Product());&nbsp; &nbsp; orderedProducts.Add(new Product());&nbsp; &nbsp; orderedProducts.Add(new Product());&nbsp; &nbsp; orderedProducts.Add(new Product());&nbsp; &nbsp; orderedProducts.Add(new Product());&nbsp; &nbsp; //orderedProducts.Add(new Product());//Add this in and you will see a result at index 5&nbsp; &nbsp; //orderedProducts.Add(new Product());&nbsp; &nbsp; //orderedProducts.Add(new Product());//7&nbsp; &nbsp; //orderedProducts.Add(new Product());&nbsp; &nbsp; //orderedProducts.Add(new Product());&nbsp; &nbsp; //orderedProducts.Add(new Product());//10&nbsp; &nbsp; var myProducts = orderedProducts.Where((pr, i) => indexes.Any(x => x == i)).ToList();}public class Product{}取消注释产品,您将获得5个预期结果。基于0的数组上的10的索引。
随时随地看视频慕课网APP
我要回答