2 回答

TA貢獻1815條經(jīng)驗 獲得超13個贊
為什么不只是indexes.Where(i => i < orderedProducts.Count).Select(i => orderedProducts[i]).ToList();
?

TA貢獻1757條經(jīng)驗 獲得超7個贊
您在測試中錯過了一些東西。您說“myProducts.Count總是大于索引列表的最大值”??紤]到您說“ myProducts僅包含2個元素”,這沒有任何意義。orderedProducts.Count必須小于6。這就是問題所在。您只需通過比較列表中的索引來提取元素。您可以通過將更多產(chǎn)品添加到列表中來“解決”該問題。
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
{
}
取消注釋產(chǎn)品,您將獲得5個預(yù)期結(jié)果。基于0的數(shù)組上的10的索引。
- 2 回答
- 0 關(guān)注
- 158 瀏覽
添加回答
舉報