Common LINQ Usages

2010-05-23

Some common methods of LINQ API that can be used in your application ther by avoid using the loops.

Use System.Linq; namespace

Sum In LINQ:

List packages =

new List

{

new Package { Company = "Coho Vineyard", Weight = 25.2 },

new Package { Company = "Lucerne Publishing", Weight = 18.7 },

new Package { Company = "Wingtip Toys", Weight = 6.0 },

new Package { Company = "Adventure Works", Weight = 33.8 }

};



double totalWeight = packages.Sum(pkg => pkg.Weight);




To find the Minimum value of a collection:

List lstRates = activity.LstRatesOfSubContractors;



Decimal minimumRate = lstRates.Min(x => x.Rate);






Where usage:

IMaterialRequirementManager manager = PSHBusinessFactory.CreateMaterialRequirementManager();

List lst = manager.GetmaterialRequirementReport(Convert.ToDateTime("1995-12-28"), Convert.ToDateTime("2012-12-06"), null, false);



IEnumerable filteredList = lst.Where(x => x.AccrueDate == dtCurrentAccureDate);



foreach (MaterialRequirementReportInfo obj in filteredList)

{



//////////////////////////

/////////////////////////

}








Enumerable.Range Method to populate the dropdown

To populate the dropdown of years like Date Of Birth


ddlDOB.DataSource = Enumerable.Range(1950, 60);

ddlDOB.DataBind();

ddlDOB.Items.Insert(0, new ListItem("--Select--", "0"));





From 1950 to 2009 it will list in the dropdown

0 comments: