[英]LINQ ToArray() with conditional
Given the following dataset: 给定以下数据集:
WharehouseId Sku OnHold InStock
===========================================
1 ABC-123 N 20
2 ABC-123 N 13
3 ABC-123 Y 4
4 ABC-123 N 18
I need to create an int[]
array that returns the InStock
items, but the value should be 0
if OnHold
equals 'Y'
. 我需要创建一个返回
InStock
项目的int[]
数组,但是如果OnHold
等于'Y'
,则该值应为0
。 So in the dataset above, the array result should be: 因此,在上面的数据集中,数组结果应为:
{ 20, 13, 0, 18 }
I am able to accomplish this by the following: 我可以通过以下方式完成此任务:
int[] inStockQty = new int[4];
int i = 0;
foreach (var item in query)
{
inStockQty[i] = item.OnHold == 'N' ? item.InStock : 0;
i++;
}
But I'm wondering if there is also a way to do this using LINQ's ToArray()
? 但是我想知道是否还有一种使用LINQ的
ToArray()
做到这一点的方法?
您可以将条件移到LINQ的Select
,如下所示:
var inStockQty = query.Select(item => item.OnHold == 'N' ? item.InStock : 0).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.