0

我想对组、语言和 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();
    }
4

3 回答 3

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
于 2013-10-31T20:23:46.140 回答
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();

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

于 2013-10-31T20:24:52.833 回答
1

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

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

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

于 2013-10-31T20:51:32.740 回答