C# SelectMany的用法

1、建立如下类:
    /// <summary>
    /// 年级
    /// </summary>
    public class Grade
    {
        /// <summary>
        /// 年级名
        /// </summary>
        public string GradeName { get; set; }
        /// <summary>
        /// 班级学生数据
        /// </summary>
        public List<Class> ClassList { get; set; }
    }
    /// <summary>
    /// 班级学生
    /// </summary>
    public class Class
    {
        public string Name { get; set; }
        public string Sex { get; set; }
    }

 

2、数据模型如下:

 public IEnumerable<Class> Test()
        {
            var classA = new List<Class>()
            {
              new Class() { Name = "James", Sex = "" },
              new Class() { Name = "Alice", Sex = "" },
              new Class() { Name = "Tom", Sex = "" }
            };
            var classB = new List<Class>()
            {
              new Class() { Name = "王明", Sex = "" },
              new Class() { Name = "李子一", Sex = "" },
              new Class() { Name = "正虎", Sex = "" }
            };
            var gradeList = new List<Grade>()
            {
                 new Grade(){ GradeName="四年级",ClassList=classA},
                 new Grade(){ GradeName="五年级",ClassList=classB}
            };
            var data = gradeList.SelectMany(c => c.ClassList);
            return data;
        }

返回结果将会把所有班级合并在一起

posted @ 2023-03-10 15:02  James·wang  阅读(237)  评论(0编辑  收藏  举报