jimmyjambles
jimmyjambles

Reputation: 1670

Lambda expression for multiple foreach loops

I would like to run GetResults() on all possible combinations of groups, languages and TestEnum. How can I re-write this code using lambda expressions to avoid using the foreach loops?

    public enum TestEnum
    {
        ONE,
        TWO,
        THREE
    }

    public static void Test1()
    {
        List<string> groups = new List<string>() { "group1", "group2", "group3", "group4" };
        List<string> languages = new List<string>() { "EN-CA", "FR-CA" };
        List<string> results = new List<string>();

        foreach (string group in groups)
        {
            foreach (string language in languages)
            {
                foreach (TestEnum enumval in Enum.GetValues(typeof(TestEnum)))
                {
                    results.Add(GetResult(group, language, enumval));
                }
            }
        }

    }
    public static string GetResult(string group, string language, TestEnum enumval)
    {
        return group + language + enumval.ToString();
    }

Upvotes: 0

Views: 1774

Answers (3)

Mike Goodwin
Mike Goodwin

Reputation: 8880

I tend to agree with lazyberezovsky, query syntax is easier to read in this case, but here goes:

results = groups
  .SelectMany(group => languages
     .SelectMany(language => Enum.GetValues(typeof(TestEnum))
        .Cast<TestEnum>()
           .Select(enumValue => GetResult(group, language, enumValue))))
  .ToList();

Maybe with better indentation or line breaks it would look nicer...

Upvotes: 1

felipekm
felipekm

Reputation: 2910

Hope this solve your problem:

var results = (
    from @group in groups 
    from language in languages 
    from TestEnum enumval in Enum.GetValues(typeof (TestEnum)) 
         select GetResult(@group, language, enumval)).ToList();

Let me know if your need some explanation.

Upvotes: 2

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

I think query syntax here is better than lambdas:

results = (from g in groups
           from l in languages
           from e in Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>()
           select g + l + e).ToList();

Produces

group1EN-CAONE
group1EN-CATWO
group1EN-CATHREE
group1FR-CAONE
group1FR-CATWO
group1FR-CATHREE
group2EN-CAONE
group2EN-CATWO
group2EN-CATHREE
etc

Upvotes: 6

Related Questions