Practical usage of Find<T> Method in Generic List<T> using Predicate
In this article we are going to see the Practical usage of Find<T> Method in Generic List<T> using Predicate.
Step 1:
Used Namespaces:
using System; using System.Collections.Generic;
Step 2:
Used Collection for demo:
// <summary> /// This is static collection used in this tutorials /// </summary> /// <returns></returns> private List<CompanyProduct> AddCollection() { List<CompanyProduct> list = new List<CompanyProduct>(); list.Add(new CompanyProduct("MS Word", 1, "Microsoft", new DateTime(2012, 10, 31))); list.Add(new CompanyProduct("MS Excel", 2, "Microsoft", new DateTime(2011, 10, 31))); list.Add(new CompanyProduct("MS Powerpoint", 3, "Microsoft", new DateTime(2010, 10, 31))); list.Add(new CompanyProduct("Visual Studio", 2, "Microsoft", new DateTime(2011, 10, 31))); list.Add(new CompanyProduct("Sql Server", 3, "Microsoft", new DateTime(2010, 10, 31))); list.Add(new CompanyProduct("Oracle", 4, "Oracle", new DateTime(2011, 10, 31))); list.Add(new CompanyProduct("Sharepoint", 6, "Microsoft", new DateTime(2012, 10, 31))); list.Add(new CompanyProduct("MS Outlook", 7, "Microsoft", new DateTime(2011, 10, 31))); return list; }
Step 3:
Printing the collection:
List<CompanyProduct> list = AddCollection(); PrintList(list, "Available Collection");
Filtering the first product by company name using Predicate //Filter the first product by company name. CompanyProduct cp = list.Find(delegate(CompanyProduct item) { return item.CompanyName == "Microsoft"; });