LINQ分组: IEnumerable<IGrouping<int, Dog>> listGroup = from dog in listDogs where dog.Age > 5 group dog by dog.Age; 遍历分组: foreach (IGrouping<int, Dog> group in listGroup) { Console.WriteLine(group.Key+"岁组:"); foreach (Dog d in group) { Console.WriteLine(d.Name + ",age=" + d.Age); } }
最后:LINQ 查询语句 编译后会转成 标准查询运算符
#region 9.0 Linq 语句 /// <summary> /// 9.0 Linq 语句 : 编译后,会生成 对应 的 标准查询 运算符! 所以说,Linq只是类似与sql的一种更加友好的 语法糖 语法而已。 /// </summary> static void TestLinq() { List<C01Dog> list = GetDogList(); List<C02DogToy> listToys = GetDogToyList(); //9.1 从 老集合中 查询 每一个 元素(d) 存入 新集合 var dogs1 = from d in list select d; //9.2 where条件 从 老集合中 查询 所有 Gender = falser 的 元素,存入 新集合 //var dogs2 = select d from d in list where d.Gender == false ; var dogs2 = from d in list where d.Gender == false select d; //9.3 排序条件 var dogs3 = from a in list orderby a.Age orderby a.ID orderby a.Name descending select a; //9.4 连接查询 注意:连接条件 使用 equals 关键字!!! var joinedList = from a in list join t in listToys on a.ID equals t.DogID select new { Dog = a, Toy = t }; foreach (var item in joinedList) { Console.WriteLine(item.ToString()); } Console.WriteLine("分组啦~~~-----------------------"); //9.5 分组查询 var groupList = from d in list group d by d.Gender; foreach (var group in groupList) { Console.WriteLine(group.Key.ToString()); foreach (var item in group) { Console.WriteLine(item.ToString()); } } //foreach (var d in list) } #endregion