如何用拉姆達表達式代替foreach進行結果篩選
ProductModel productmodel = new ProductModel();
int? prostate_0 = 0;
int? prostate_1 = 0;
int? prostate_2 = 0;
productmodel.Shop = _Shop;
List<ProductModel> listcount = productmodel.Listcount();
foreach (ProductModel item in listcount)
{
if (item.Pro_stateNum != null)
{
switch (item.Pro_state)
{
case 0:{
prostate_0 = item.Pro_stateNum;
} break;
case 1:{
prostate_1 = item.Pro_stateNum;
} break;
case 2:{
prostate_2 = item.Pro_stateNum;
} break;
}
}
}
還可以簡化下
List<ProductModel> listcount = productmodel.Listcount();
->
List<ProductModel> listcount = productmodel.Where(x => x.Pro_stateNum != null).Listcount();
productmodel.ForEach((item) => {
switch (item.Pro_state)
{
case 0:{
prostate_0 = item.Pro_stateNum;
} break;
case 1:{
prostate_1 = item.Pro_stateNum;
} break;
case 2:{
prostate_2 = item.Pro_stateNum;
} break;
}
});