LINQ查询表达式---------into

LINQ查询表达式---------into

into 上下文关键字创建一个临时标识符,以便将 group、join 或 select 子句的结果存储到新的标识符

class Program
{
    public class PerInfo
    {
        public int Id
        {
            get;
            set;
        }
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
    }

    static void Main(string[] args)
    {
        //into 上下文关键字创建一个临时标识符,以便将 group、join 或 select 子句的结果存储到新的标识符
        List<PerInfo> perInfos = new List<PerInfo>
        {
            new PerInfo{Id = 1, Name = "小日", Age = 15},
            new PerInfo{Id = 2, Name = "小日", Age = 17},
            new PerInfo{Id = 3, Name = "张三", Age = 21},
            new PerInfo{Id = 4, Name = "李四", Age = 23}
        };

        //into用于select
        var query1 = from q in perInfos
                     where q.Id > 1
                     select new
        {
            NewName = q.Name, NewAge = q.Age
        }
        into NewPerInfo
        orderby NewPerInfo.NewAge descending
        select NewPerInfo;
        Console.WriteLine("into 用于 select");
        foreach (var item in query1)
        {
            Console.WriteLine("    {0}   {1}", item.NewName, item.NewAge);
        }


        //into 用于group
        var query2 = from p in perInfos
                     group p by p.Name[0] into g//使用 into 关键字来启用临时标识符 g,该标识符具有推断类型 IGroupi
                     select g;
        Console.WriteLine("into 用于group");
        foreach (var key in query2)
        {
            Console.WriteLine("  分组键:{0}", key.Key);
            foreach (var item in key)
            {
                Console.WriteLine("    {0}  {1}", item.Name, item.Age);
            }
        }

        Console.ReadLine();
    }
}
输出结果:
into 用于 select
    李四   23
    张三   21
    小日   17
into 用于group
  分组键:小
    小日  15
    小日  17
  分组键:张
    张三  21
  分组键:李
    李四  23

  

posted @ 2017-03-03 17:37  涂山吕吕  阅读(575)  评论(0编辑  收藏  举报