C# linq foreach for
int number = 0; //比數
List<testPriceModel> returnData = new List<testPriceModel>(); //輸出資訊
List<testPriceModel> testInData = new List<testPriceModel>(); //預設資訊
testInData.Add(new testPriceModel { id = "1" ,name = "A" ,price = 50 });
testInData.Add(new testPriceModel { id = "2" ,name = "BB" ,price = 90 });
testInData.Add(new testPriceModel { id = "3" ,name = "CCC" ,price = 30 });
testInData.Add(new testPriceModel { id = "4" ,name = "DDDD" ,price = 45 });
testInData.Add(new testPriceModel { id = "5" ,name = "EEEEE" ,price = 77 });
//範例1:linq
returnData = testInData.Where(o => o.price <= 55 && o.id != "3").ToList();
number = returnData.Count();
//範例2:foreach
foreach (var p in testInData)
{
if ((p.price <= 55) && (p.id != "3"))
{
returnData.Add(p);
}
}
number = returnData.Count();
//範例3:for
for (int i = 0; i < testInData.Count(); i++)
{
if ((testInData[i].price <= 55) && (testInData[i].id != "3"))
{
returnData.Add(testInData[i]);
}
}
number = returnData.Count();
我只是一棵樹