Saturday, August 29, 2009

How to use list.find<> and list.findall<> in System.Collections.Generic

List.find<>
This will return first matched item from the list.
List. FindAll<>
This will return all matching items from the list.

Item Class Code
class Item
{
public int Amount;
public string Name;
}

List<Item> listItem = new List<Item>();
 
Item T1 = new Item() { Name = "A", Amount = 100 };
Item T2 = new Item() { Name = "B", Amount = 600 };
Item T3 = new Item() { Name = "C", Amount = 100 };
Item T4 = new Item() { Name = "D", Amount = 150 };
Item T5 = new Item() { Name = "E", Amount = 200 };
 
listItem.Add(T1);
listItem.Add(T2);
listItem.Add(T3);
listItem.Add(T4);
listItem.Add(T5);
Method 1
Item Result= listItem.Find(P=>P.Name=="A");
// item having "A" as it's item name
 
Item Result= listItem.Find(P=>(P.Name=="A" & P.Amount==100));
// item having "A" as it's item name and Amount as 100
 
Item Result= listItem.FindAll(P=>P.Amount==100);
//items having Amount as 100
Method 2
You can write your own function for searching.
private bool findItem(Item I) 
{
if (I.Name == "A")
{ return true; }
else
{ returnfalse;}
}
 
Item Result= listItem.Find(findItem);
Post a Comment