Amazon.com Widgets All posts tagged 'lambda'

WilliaBlog.Net

I dream in code

About the author

Robert Williams is an internet application developer for the Salem Web Network.
E-mail me Send mail
Code Project Associate Logo
Go Daddy Deal of the Week: 30% off your order at GoDaddy.com! Offer expires 11/6/12

Recent comments

Archive

Authors

Tags

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.


Use lambda expressions to aggregate values into a delimited string

Let's say you need to aggregate one value from each object in a list into a single string. For Example, you want to send an e-mail to a set of customers. This requires a string with the email addresses seperated by a semicolon (;). The following code will create a generic List of Books, and provide a method ListAllEmails() that will print the delimited list of emails to the console window:

 

namespace ConsoleApplication1

{

    using System;

    using System.Collections.Generic;

    using System.Linq;

 

    public class Lambdas

    {

        /// <summary>

        /// Define the Book Class

        /// </summary>

        public class Book

        {

            public string Title { get; set; }

            public string Author { get; set; }

            public double Price { get; set; }

            public string EmailAddress { get; set; }

        }

 

        public List<Book> Books { get; private set; }

 

        public Lambdas()

        {

            // Create a new list of Books

            Books = new List<Book> {

                new Book { Title = "Pro ASP.Net MVC Framework", Author = "Steven Sanderson", Price = 49.99, EmailAddress = "steve@nospam.com" },

                new Book{ Title = "Pro Silverlight 2 in C# 2008", Author = "Matthew MacDonald", Price = 49.99, EmailAddress = "Matthew@nospam.com" },

                new Book{ Title = "Pro VB 2008 and the .Net 3.5 Platform", Author = "Andrew Troelsen", Price = 59.99, EmailAddress = "Andrew@nospam.com" }

            };

        }

 

        /// <summary>

        /// Creates a semicolon (;) delimited list of email addresses

        /// </summary>

        public void ListAllEmails()

        {

            Console.WriteLine(this.Books.Select(b => b.EmailAddress).Aggregate((items, item) => items + "; " + item));

            // output= "steve@nospam.com; Matthew@nospam.com; Andrew@nospam.com"

        }

    }

}

 

The Select Method selects the EmailAddress for each Book. The Aggregate method builds a list of the items based on the lambda expression. Notice that this did not require any additional code to ensure there is no extra semi-colon at the beginning or end of the list, which is often required when using a loop to concatenate text.

 

Note: Be careful when using the Aggregate method because it is very inefficient on large numbers of strings. Consider using the String Join method instead.

 

In VB, the lambda would look like this:

 

   Console.WriteLine(Books.Select(Function(b) b.EmailAddress).Aggregate(Function(items, item) items & "; " & item))

 

You can also filter the list of email addresses. For Example, suppose you want to send an email to all the authors who sell their books for under $50, telling them that you think you can sell their next book for $59.99:

 

        /// <summary>

        /// Creates a semicolon (;) delimited list of email addresses where the price of the book is under $50

        /// </summary>

        public void ListSomeEmails()

        {

            Console.WriteLine(this.Books.Where(b => b.Price < 50).Select(b => b.EmailAddress).Aggregate((items, item) => items + ", " + item));

            // output= "steve@nospam.com, Matthew@nospam.com"

        }

 

Let's take this one step further. Suppose you wanted to create a comma separated list of values and replace the last comma with " and", so that a single item would be "item1", two items would be "item1 and item2", three items would be "item1, item2 and item3", etc.

 

        /// <summary>

        /// Creates a comma delimited list of email addresses and replaces the last comma with " and "

        /// </summary>

        public void ListEmailsAsSmartCsv()

        {

            string csv = this.Books.Select(b => b.EmailAddress).Aggregate((items, item) => items + ", " + item);

            Console.WriteLine(Regex.Replace(csv, @",\s([^,]+)$", " and $1"));

            // output= "steve@nospam.com, Matthew@nospam.com and Andrew@nospam.com"

        }

 

 


Tags:
Categories: ASP.Net | C# | VB
Posted by Williarob on Friday, February 26, 2010 9:44 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Simplify Your Code with Lambda Expressions

Most applications retain lists of things, and a common task is to find an item in that list. The following class illustrates three ways to find an item in a generic list:

 

namespace ConsoleApplication1

{

    using System;

    using System.Collections.Generic;

    using System.Linq;

 

    public class Lambdas

    {

        public class Book

        {

            public string Title { get; set; }

            public string Author { get; set; }

            public double Price { get; set; }

        }

 

        public List<Book> Books { get; private set; }

 

        public Lambdas()

        {

            Books = new List<Book> {

                new Book { Title = "Pro ASP.Net MVC Framework", Author = "Steven Sanderson", Price = 49.99 },

                new Book{ Title = "Pro Silverlight 2 in C# 2008", Author = "Matthew MacDonald", Price = 49.99},

                new Book{ Title = "Pro VB 2008 and the .Net 3.5 Platform", Author = "Andrew Troelsen", Price = 59.99 }

            };

        }

 

        /// <summary>

        /// Returns a book using a traditional loop

        /// </summary>

        private Book FindUsingTraditionalLoop(string title)

        {

            Book foundBook = null;

 

            foreach (var b in this.Books)

            {

                if (b.Title == title)

                {

                    foundBook = b;

                    break;

                }

            }

 

            return foundBook;

        }

 

        /// <summary>

        /// Returns the book using a Linq expression

        /// </summary>

        private Book FindUsingLinq(string title)

        {

            var query = from b in this.Books

                        where b.Title == title

                        select b;

 

            return query.Count() > 0 ? query.ToList()[0] : null;

        }

 

        /// <summary>

        /// Returns the book using a Lambda expression

        /// </summary>

        private Book FindUsingLambda(string title)

        {

            return this.Books.FirstOrDefault(b => b.Title == title);

        }

 

        public void Test()

        {

            Console.WriteLine("Found: {0}", this.FindUsingTraditionalLoop("Pro Silverlight 2 in C# 2008").Author);

            Console.WriteLine("Found: {0}", this.FindUsingLinq("Pro Silverlight 2 in C# 2008").Author);

            Console.WriteLine("Found: {0}", this.FindUsingLambda("Pro Silverlight 2 in C# 2008").Author);

        }

    }

}

As these examples show, you can save time reading and writing your code by using Lambda expressions to find items in a list.

For VB programmers, the syntax of the Lambda expression looks like this:

return Me.Books.FirstOrDefault(Function(b) b.Title = title)


Categories: ASP.Net | C# | VB
Posted by Williarob on Wednesday, January 06, 2010 8:10 AM
Permalink | Comments (0) | Post RSSRSS comment feed