c# - 将嵌套在 ForEach 循环中的 for 循环转换为 LINQ

标签 c# linq

我在以下代码中遇到编译错误“并非所有代码路径都返回一个值”,这是怎么回事?!

 public class SomeEntity
    {
        public int m_i;
        public SomeEntity(int i)
        {
            m_i = i;
        }

        public override string ToString()
        {
            return m_i.ToString();
        }


        public static int someFunction(int i) { return i + 100; }

        public static IEnumerable GetEntities()
        {
            int [] arr = {1,2,3};
            foreach (int i in arr)
            {

                //        for (int i = 0; i < someArray.Count();i++)
                //            yield return new SomeEntity(someFunction(i));

                // *** Equivalent linq function ***    
                return Enumerable.Range(0, 7).Select(a => new SomeEntity(someFunction(a)));
            }
        }
    }

这个我也想不通。。。 我尝试将外部 foreach 循环转换为 linq 表达式

public static IEnumerable GetEntities()
        {
            int [] arr = {1,2,3};

            return arr.Select(Xenv =>
                 Enumerable.Range(0, 7).Select(a => new SomeEntity(someFunction(a)))
                );
        }

但后来我得到了一个错误:/

最佳答案

因为 arr 可能为空,因此您不会在 foreach 循环内返回。在 foreach 循环之后放一个 return。

public static IEnumerable GetEntities()
{
    int[] arr = { 1, 2, 3 };
    foreach (int i in arr)
    {

        //        for (int i = 0; i < someArray.Count();i++)
        //            yield return new SomeEntity(someFunction(i));

        // *** Equivalent linq function ***    
        return Enumerable.Range(0, 7).Select(a => new SomeEntity(someFunction(a)));
    }
    return Enumerable.Empty<int>(); // <<<< this is what you need
}

关于c# - 将嵌套在 ForEach 循环中的 for 循环转换为 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39267469/

相关文章:

c# - 从 DataGridCell 获取控件

c# - Dispose 会处理仍然被引用的对象?

c# - 用户定义类列表错误 "Failed to compare two elements in the array"

c# - c# 可以像 VB.NET 一样自动更正语法大小写吗?

c# - 什么是轻量级事件?

c# - 使用 LINQ 按小时分组

c# - 如何将 List<Bear> 或 List<Goat> 分配给 List<IAnimal>

.net - order by后如何从每组中选择前1名

c# - 使用 LINQ 将三个列表连接成一个会引发异常

c# - 将 char * 发送到字符串 c#