linq to object

 查询内存对象--Linq to object    

      1高级查询

       2限定符操作
       3元素操作
       4类型转换操作
       5 使用linq操作集合
       6使用linq操作字符

       7使用linq操作文件


 

 protected void Page_Load(object sender, EventArgs e)
    {
        List<Person> person = new List<Person> { new Person(1, "lx",18), new Person(2, "lx2",22), new Person(3, "lx3",30) };
        person.ForEach(p => Response.Write("(" + p.ID.ToString() + "," + p.Name.ToString() + ","+p.Age.ToString()+")<br/>"));
        bool result = person.All(p=>p.Age>30);
        Response.Write("result: "+result.ToString()+"<br/>");

        bool result2 = person.Count(p=>p.Age>30)==person.Count;
        Response.Write("result: " + result2.ToString() + "<br/>");
        person.Reverse();
        foreach (var item in person)
        {
            item.Name = item.Name + " u ";
            Response.Write("(" + item.ID.ToString() + "," + item.Name.ToString() + "," + item.Age.ToString() + ")<br/>");
        }
        bool result3 = person.Any(p => p.Age >= 30);
       
        Response.Write("any result: " + result3.ToString() + "<br/>");

        bool result4 = person.Exists(p => p.Age < 30);
        Response.Write("existes result: " + result4.ToString() + "<br/>");
        bool result5 = person.Contains(new Person(1, "lx", 18));
        Response.Write("contains result: " + result5.ToString() + "<br/>");

        Person model=person.First();
        Response.Write(" first() result: " + model.Name+","+model.ID+","+model.Age + "<br/>");


        var queryp = from p in person.AsEnumerable<Person>() where p.ID<4 select new { ID = p.ID, Name = p.Name };
        foreach (var item in queryp)
        {
            Response.Write("<>---------person: "+item+"<br/>");
        }

        var queryps = from p in person.AsQueryable<Person>() where p.Name.IndexOf("lx")>-1 select new { ID = p.ID, Name = p.Name };
        foreach (var item in queryps)
        {
            Response.Write("<>-----ps----person: " + item + "<br/>");
        }

       // Person model2 = person.Single(p=>p.Name=="lx");
       //if(model2!=null)
       // Response.Write("Single result: " + model2.Name + "," + model2.ID + "," + model2.Age + "<br/>");

        int[] ints = Enumerable.Range(0, 10).ToArray();
        StringBuilder sb = new StringBuilder("ints={");
        foreach (var item in ints)
        {
            sb.Append(item.ToString() + ",");  
        }
        if (sb.Length > 0)
        {
            sb.Remove(sb.Length-1,1);
        }
        sb.Append("}");
        Response.Write("ints[]= " + sb.ToString());


        var m = from n in ints where n < 5 orderby n select n;
        foreach (var n in m)
        {
            Response.Write("n=" + n+"<br/>");
        }

        string[] strs = Enumerable.Repeat("9",3).ToArray();
        StringBuilder sb2 = new StringBuilder(" strs ={");
        foreach (var item in strs)
        {
            sb2.Append(item.ToString() + ",");
        }
        if (sb2.Length > 0)
        {
            sb2.Remove(sb2.Length - 1, 1);
        }
        sb2.Append("}");
        Response.Write("ints[]= " + sb2.ToString());


        // join 查询
        List<SaleBill> bills = new List<SaleBill> { new SaleBill("lx01","lx1",Convert.ToDateTime("2013-2-1")),
                                                    new SaleBill("lx02","lx2",Convert.ToDateTime("2013-3-4"))
                                                  };
        List<SaleProduct> products = new List<SaleProduct>{
            new SaleProduct("lx01","冰箱",1,2000),
            new SaleProduct("lx02","洗衣机",1,1300)
        };

        var query = bills.Join(products, k => k.SaleBillCode, p => p.SaleBillCode, (k, p) => new { 销售单号 = k.SaleBillCode, 销售日期 = k.SaleDate, 销售员 = k.SaleMan, 销售商品 = p.ProductName, 数量 = p.Quantity, 价格 = p.Price, 金额 = p.Price * p.Quantity });
        this.GridView1.DataSource = query;
        this.GridView1.DataBind();

         //var query2 = from b in bills join p in products on b.SaleBillCode equals p.SaleBillCode into pGrop from pItem in pGrop.DefaultIfEmpty(new SaleProduct("", "", 0, 0)) select new { 销售单号 = b.SaleBillCode, 销售日期 = b.SaleDate, 销售员 = b.SaleMan, 销售商品 = pItem.ProductName, 数量 = pItem.Quantity, 价格 = pItem.Price, 金额 = pItem.Price * pItem.Quantity };
         //this.GridView2.DataSource = query2;
         //this.GridView2.DataBind();

        var query2 = from b in bills from p in products select new { 销售单号 = b.SaleBillCode, 销售日期 = b.SaleDate, 销售员 = b.SaleMan, 销售商品 = p.ProductName, 数量 = p.Quantity, 价格 = p.Price, 金额 = p.Price * p.Quantity };//from b in bills join p in products on b.SaleBillCode equals p.SaleBillCode into pGrop from pItem in pGrop.DefaultIfEmpty(new SaleProduct("", "", 0, 0)) select new { 销售单号 = b.SaleBillCode, 销售日期 = b.SaleDate, 销售员 = b.SaleMan, 销售商品 = pItem.ProductName, 数量 = pItem.Quantity, 价格 = pItem.Price, 金额 = pItem.Price * pItem.Quantity };
        this.GridView2.DataSource = query2;
        this.GridView2.DataBind();

        //操作 arrylist集合  查询非泛型集合
        ArrayList arraylist = new ArrayList();
        for (int i = 0; i < 100; i++)
        {
            arraylist.Add(i.ToString());
        }
       
        var queryarrylist = from i in arraylist.Cast<string>() where i.IndexOf("0") > -1 select i;
        foreach (var item in queryarrylist)
        {
            Response.Write("<br/> cast------"+item+" ,");
        }

        //筛选指定元素
        var queryarrylist2 = from i in arraylist.OfType<string>() where i.IndexOf('3')>0 select i;
        foreach (var item in queryarrylist2)
        {
            Response.Write("<br/> OfType------" + item + " ,");
        }

        //排序
        var querye = person.OrderBy(p => p.Name);
        foreach (var item in querye)
        {
            Response.Write("<br/> OrderBy------" + item.Name+","+item.ID + " ;");
        }

        //操作泛型 字典 Dictionary
        Dictionary<int, Person> user = new Dictionary<int, Person>();
        user.Add(1, person[0]);
        user.Add(2, person[1]);
        user.Add(3, person[2]);
        
        var tquery2=from item in user select new {键值=item.Key,用户名=item.Value.Name};
        var tquery = from item in user where item.Value.Name.CompareTo("lx") > 0 orderby item.Key descending select item;
        foreach (var item in tquery)
        {
            Response.Write("dictionary:-1-<hr> "+string.Format("id={0},person.Name={1}",item.Key,item.Value.Name+"<br/>"));
        }

        foreach (var item in tquery2)
        {
            Response.Write("dictionary:-2-<hr> " +   item + "<br/>" );
        }

        //操作泛型 排序字典
        SortedDictionary<int, Person> users = new SortedDictionary<int, Person>();
        users.Add(1, person[0]);
        users.Add(2, person[1]);
        users.Add(3, person[2]);

        var tqueryt = from item in users orderby item.Value.Name.ToUpper() select new { 键值 = item.Key, 用户名 = item.Value.Name.ToUpper() };
        foreach (var item in tqueryt)
        {
            Response.Write("SortedDictionary:--<hr> " +  item  + "<br/>");
        }

        //linq操作泛型哈希集 hashSet<T>
        HashSet<Person> persons = new HashSet<Person>();
        persons.Add(person[0]);
        persons.Add(person[1]);
        persons.Add(person[2]);

        var queryHash = from item in persons orderby item.Name, item.ID select item;
        foreach (var item in queryHash)
        {
            Response.Write(string.Format("id={0} name={1}",item.ID,item.Name+"<br/>"));
        }


        //linq 操作字符
        string strSource = "Wang Fei And Li Ya Peng !..... 520  1314 ! $%^*#@ |";
        var queryStr=from s in strSource where  char.IsUpper(s) select s;
        foreach (var item in queryStr)
        {
            Response.Write("<br/>-isUpper---" + item.ToString());
        }
        
        var queryDigit=from s in strSource where char.IsDigit(s) select s;
        foreach (var item in queryDigit)
        {
            Response.Write("<br/>-Digit---" + item.ToString());
        }

        var queryLetter = from s in strSource where char.IsLetter(s) select s;
        foreach (var item in queryLetter)
        {
            Response.Write("<br/>-Letter---" + item.ToString());
        }


        var queryPunctuation = from s in strSource where char.IsPunctuation(s) select s;
        foreach (var item in queryPunctuation)
        {
            Response.Write("<br/>-Punctuation---" + item.ToString());
        }

        var queryIsSeparator = from s in strSource where char.IsSeparator(s) select s;
        foreach (var item in queryIsSeparator)
        {
            Response.Write("<br/>-Separator---" + item.ToString());
        }

        var queryIsSymbol = from s in strSource where char.IsSymbol(s) select s;
        foreach (var item in queryIsSymbol)
        {
            Response.Write("<br/>-Symbol---" + item.ToString());
        }


        var queryWF=from letter in strSource let words=strSource.Split('!') where  words.Contains("Fei") select letter;
        Response.Write("----------"+queryWF);


        strSource = @"The number of really big game releases - known as  triple A games . - is slowly decreasing with the move towards mobile devices for gaming.
                     But this also creates a great opportunity .for smaller developers to make a breakthrough into the industry by offering their content for lower prices, or even free.
                     With an average of $5 for 10 games, Spencer Kelly explores the idea of pay what you want moving to the gaming world.";
        string matches = "of";
        string[] sentences = strSource.Split(new char[] { '.', '?', ',', '!' });
        var queryOF = from item in sentences
                      let words = item.Split(new char[] { '.', '?', ',', ':',';', '!' }, StringSplitOptions.RemoveEmptyEntries)
                      where words.Contains(matches)
                      select item;
        foreach (var item in queryOF)
        {
            Response.Write("<br/>----------Contains---" + item.ToString());
        }
    
    }

 

 

 

 

 public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
     
            int[] ary = { 1, 2, 3, 4, 5 };
            var query1=from ia in ary where ia>1 where ia<5 select ia ;
            foreach (var item in query1)
            {
              Response.Write(item);
            }

            student[] stAry = { new student("zhangsan", "man", 20), new student("lisi", "man", 30), new student("lx", "women", 22) };
            var query2 = from student stu in stAry select stu;
            foreach (var stu in query2)
            {
                Response.Write("<br/>"+stu.ToString());
            }


            int[] ary2 = { 0, 9, 22, 33, 24, 15, 68, 89, 44, 78 };
            var query4 = from int t in ary2 orderby t where t>0 where t<100 select t;
            foreach (var item in query4)
            {
                Response.Write("+<br/>"+item);
            }
            //var query3 = from student stu in stAry select stu.Name.Length;
            //foreach (int item in query3)
            //{
            //}

            var query5=from student stu in stAry group stu by  stu.XingBie;
            foreach (var grp in query5)
            {
                Response.Write("<br/>---------" + grp.Key);
                foreach (var var1 in grp)
                {
                    Response.Write("-------------- <br/>" + var1);
                }
            }

            var query6 = from student stu in stAry group stu by stu.Age into stGrp orderby stGrp.Key descending select stGrp;
            foreach (var stGrp in query6)
            {
                Response.Write("<br/>年龄分组。。并降序。。"+stGrp.Key+"岁的人");
                foreach (var var1 in stGrp)
                {
                    Response.Write("  "+var1);
                }
            }

 


            student[] stus ={
                               new student("张三","男",22,new List<LessonScore>{ new LessonScore("math",80.9f), new LessonScore("english",82.9f)}),
                               new student("李四","男",23,new List<LessonScore>{ new LessonScore("math",80.9f), new LessonScore("english",90.9f)}),
                              new student("王五","男",23,new List<LessonScore>{ new LessonScore("math",80.9f), new LessonScore("english",80.9f)}),
                              new student("龙虾","男",23,new List<LessonScore>{ new LessonScore("math",60.9f), new LessonScore("english",76.9f)}),
                             new student("龙心","女",21,new List<LessonScore>{ new LessonScore("math",98.9f), new LessonScore("english",56.9f)}),
                             new student("花生","男",24,new List<LessonScore>{ new LessonScore("math",40.9f), new LessonScore("english",89.9f)})
                           };

            var query7 = from stu in stus
                         from scr in stu.Scores
                         where scr.Score > 80
                         group new { stu.Name, scr } by stu.Name;

            foreach (var grp in query7)
            {
                Response.Write("<br/>---grp.key" + grp.Key);
                foreach (var item in grp)
                {
                    Response.Write("....."+item);
                }
            }

            int[] intArry1 = { 5, 15, 20, 30, 40, 50 };
            int[] intArry2 = { 10, 20, 30, 50, 60, 70, 80 };
            var query8 = from var1 in intArry1
                         join var2 in intArry2 on var1 % 5 equals var2 % 15 into var2Grp
                         from grp in var2Grp.DefaultIfEmpty()
                         select new { VAL1 = var1, Var2GRP= grp };
            foreach (var obj in query7)
            {
                Response.Write("...."+obj);
            }


            var query9 = intArry1.Where(num => num % 2 == 0);
            foreach (var num in query9)
            {
                Response.Write("--" + num + "---");

            }
               
            var query10 = intArry1.OrderBy(num1 => num1 % 10);
            foreach (var num1 in query9)
            {
                Response.Write("--" + num1 + "---");
            }

 


        }

         class student{
             public string Name
             {
                 get;
                 set;
             }

             public string XingBie { get; set; }
             public uint Age { get; set; }
             public List<LessonScore> Scores { get; set; }
             public student(string name,string xb,uint age,List<LessonScore> scrs)
             {
                 this.Name=name;
                 this.Age=age;
                 this.XingBie=xb;
                 this.Scores=scrs;

             }

             public student(string name, string xb, uint age)
             {
                 this.Age = age;
                 this.Name = name;
                 this.XingBie = xb;
             }

             public override string ToString()
             {
                 string str;
                 str = string.Format("{0}-{1}-{2}", this.Name, this.Age, this.XingBie);
                 return str;
             }
        }

        class LessonScore
        {
            public string Lesson { get; set; }
            public float Score { get; set; }
            public LessonScore(string les, float scr)
            {
                this.Lesson = les;
                this.Score = scr;
            }

            public override string ToString()
            {
                string str;
                str = string.Format("{0}-----{1}分", this.Lesson, this.Score);
                return str;
            }


        }
    }


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值