Find and item from a generic list of items
I have a list of products and what to check if an item id match whith ID = 100 then discount 50% otherwise default one.
Decimal discount = 10;
foreach(Product item in ProductList)
{
if(item.ID == 100)
{
discount = 50;
break;
}
}
Is there any easy code to write in one line?
2 Answers
You can use where and count to check, see this
Decimal discount = 10;
if(ProductList.Where(x => x.ID == 100).Count() > 0)
discount = 50;
|
2
|
Answered:
27 Feb 2013
Reputation: 242
|
|
You can also use Find method
Product Item = ProductList.Find(m => m.ID == 100)
if(Item !=null)
discount = 50;
|
0
|
Answered:
27 Feb 2013
Reputation: 1,418
|
|
This week users
