【发布时间】:2017-05-09 11:19:21
【问题描述】:
我知道将 lambda 表达式的位置放在下一行很容易,但由于我是新手,所以我不知道。 在下面的代码中,coupon.products 有大约 27000 种产品,在下面的行中,我必须添加 where 条件,如
where p.id not in (1,2,3)
int[] productIds = (from p in coupon.Products select p.Id).ToArray<int>();
我应该如何添加另外我应该如何优化我的代码?
我试过了
int[] productIds = (from p in coupon.Products select p.Id).ToArray<int>().Where(i => i.Id not in (1,2));
试过了还是不行
List<int> excludedItems = new List<int>();
foreach (BasketItem item in basket.Items)
{
excludedItems.Add(item.Product.Id);
}
// int[] excluded = new int[] { 1, 2, 3 };
int[] productIds = coupon.Products.Where(p => excludedItems.Contains(p.Id))
.Select(p => p.Id)
.ToArray();
【问题讨论】:
-
在 ToArray 之前添加 Where ,我认为它应该可以工作。
-
@TamásSzabó 他们不会在
Id上选择然后在上面调用.Id -
没错,那么第二个 lambda 必须是
i => i not in (1, 2)。
标签: c# performance linq lambda