Sponsors

News

Jobping Laurent Kempé MVP JetBrains Academy Member Certified ScrumMaster

Contact

My status

View Laurent Kempé's profile on LinkedIn
XING
twitter
facebook


Xbox 360



Map

Locations of visitors to this page

.NET Dudes

Family

French .NET Dudes

Friends

Jobping

Links

Tech Head Brothers

The beauty of C# and Linq

Today I faced the following challenge to solve: return all possible combinations of three source collections.

We are using C# and with Linq it was just so easy.

  1. public List<string> Contexts
  2. {
  3.     get
  4.     {
  5.         var result = from u in SelectedUseCases
  6.                      from c in SelectedChannels
  7.                      from up in SelectedUserProfiles
  8.                      select string.Format("{0}-{1}-{2}", u.Value, c.Value, up.Value);
  9.  
  10.         return result.ToList();
  11.     }
  12. }

Simple and beautiful!

Posted: Jan 25 2010, 09:57 PM by lkempe | with 4 comment(s)
Filed under: ,

Comments

David Taylor said:

Yeah I love it as well.  I suppose the equivalent in C# 2 would have been:

public IEnumerable<string> Contexts

{

   get

   {

       foreach (var u in SelectedUseCases)

       foreach (var c in SelectedChannels)

       foreach (var up in SelectedUserProfiles)

        yield return string.Format("{0}-{1}-{2}", u.Value, c.Value, up.Value);

   }

}

With the exception that you would need to change var to your actual types, and I don't know what they are ;-)

Dave

# January 26, 2010 1:42 AM

lkempe said:

Dave: Right ! Looks also good in C# 2 but I do prefer the Linq syntax.

# January 26, 2010 2:52 AM

Twitter Trackbacks for The beauty of C# and Linq - Laurent Kemp?? [asp.net] on Topsy.com said:

Pingback from  Twitter Trackbacks for                 The beauty of C# and Linq - Laurent Kemp??         [asp.net]        on Topsy.com

# January 26, 2010 4:04 AM

zoldello said:

Nice. Microsoft staff are really squeezing all they can out of OOP to justify their paycheck. That is inspirational.

# January 28, 2010 12:44 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)