The following example shows how to use lambda expressions in C#. Function definitions taking lambda expressions are parameters to act on the given list or object
// function that prints the property value for the given object and property public static void PrintProperty<T, TProperty>(T t, Func<T, TProperty> ex) { // print the value of the property Console.WriteLine(“Print property:”); Console.WriteLine(ex(t)); Console.WriteLine(“”); } // function that prints a list to console with a code and description property expression public static void PrintList<T, TProperty>(List t, Func<T, TProperty> excode, Func<T, TProperty> exdescr) { Console.WriteLine(“Print list (code, description):”); // go through each item in the list foreach (var a in t) { // extract the code and description - then print var code = excode(a); var desc = exdescr(a); Console.WriteLine(String.Format(“{0}, {1}”, code, desc)); } Console.WriteLine(“”); }
Examples of calling these functions
// a test model class TestModel { public string Field1 { get; set; } public string Field2 { get; set; } } // author model class AuthorModel { public string Name { get; set; } public string Address { get; set; } } // run the example class Program { static void Example() { // define an instance of test model, print property values var t = new TestModel { Field1 = “13”, Field2 = “6” }; PrintProperty(t, x => x.Field2); PrintProperty(t, x => x.Field1); // build a list of test model, print with Field1 as code, Field2 as description var tlst = new List(); tlst.Add(new TestModel { Field1 = “1”, Field2 = “2” }); tlst.Add(new TestModel { Field1 = “2”, Field2 = “3” }); tlst.Add(new TestModel { Field1 = “1”, Field2 = “4” }); tlst.Add(new TestModel { Field1 = “3”, Field2 = “5” }); tlst.Add(new TestModel { Field1 = “1”, Field2 = “6” }); PrintList(tlst, x => x.Field1, x => x.Field2); // build a list of authors, print name as code, address as description var alst = new List(); alst.Add(new AuthorModel { Name = “Mike”, Address = “Peabody” }); alst.Add(new AuthorModel { Name = “Matt”, Address = “Wakefield” }); alst.Add(new AuthorModel { Name = “Steve”, Address = “Salem” }); alst.Add(new AuthorModel { Name = “Paul”, Address = “San Diego” }); PrintList(alst, x => x.Name, x => x.Address); } }
Output Print property: 6 Print property: 13 Print list (code, description): 1, 2 2, 3 1, 4 3, 5 1, 6 Print list (code, description): Mike, Peabody Matt, Wakefield Steve, Salem Paul, San Diego