多个foreach循环的Lambda表达式

时间:2013-10-31 20:19:14

标签: c# lambda

我想对组,语言和TestEnum的所有可能组合运行GetResults()。如何使用lambda表达式重新编写此代码以避免使用foreach循环?

    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();
    }

3 个答案:

答案 0 :(得分:6)

我认为这里的查询语法比lambdas更好:

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

可生产

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

答案 1 :(得分:2)

希望这可以解决您的问题:

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

如果您需要一些解释,请告诉我。

答案 2 :(得分:1)

我倾向于同意lazyberezovsky,在这种情况下查询语法更容易阅读,但这里有:

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

也许有更好的缩进或换行符,它看起来会更好......