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);
  10.         return result.ToList();
  11.     }
  12. }

Simple and beautiful!


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

    public IEnumerable Contexts
    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: Right ! Looks also good in C# 2 but I do prefer the Linq syntax.

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

Comments have been disabled for this content.