zoukankan      html  css  js  c++  java
  • LinqToXML

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="WebApplication1.Index" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            
            <asp:Button ID="Button1" runat="server" Text="Linq" onclick="Button1_Click" 
                style="height: 21px" />
            
            <br />
            <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="OrderBy" />
            
            <br />
            <br />
            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
            
            <asp:Button ID="Button3" runat="server" Text="子查询" onclick="Button3_Click" />
            <br />
            <asp:Button ID="Button4" runat="server" Text="连接查询" onclick="Button4_Click" />
            <br />
            <asp:Button ID="Button5" runat="server" Text="分组查询" onclick="Button5_Click" />
            <br />
            <asp:Button ID="Button6" runat="server" Text="练习" onclick="Button6_Click" />
            <br />
            <br />
            <asp:TextBox ID="TextBox1" runat="server" Width="19px">1</asp:TextBox>
            <asp:Button ID="Button7" runat="server" Text="Go" onclick="Button7_Click" />
            <br />
            <br />
            
        </div>
        </form>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebApplication1
    {
        public partial class Index : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
            #region Linq查询
            protected void Button1_Click(object sender, EventArgs e)
            {
                string[] arr = { "汪昭贵", "廖文勇", "廖梦威", "廖琴", "胡佩" };
                //查询姓名长度2的人
                var v = from r in arr
                        where r.Length == 2
                        select r;
                foreach (var item in v)
                {
                    Response.Write("<br/>" + item);
                }
                //长度为3姓廖
                var v1 = from s in arr
                         where s.Length == 3 && s.Substring(0, 1) == ""
                         select s;
                foreach (var item in v1)
                {
                    Response.Write("<br/>"+item);
                }
                       
            }
           
            //集合排序
            //*********************************数据***************************************
            
            List<Student> stus = new List<Student>()
            {
                new Student(){StuId=1001,Sex="",StuName="曾文凯",Age=18},
                new Student(){StuId=1002,Sex="",StuName="廖琴",Age=20},
                new Student(){StuId=1003,Sex="",StuName="向艳秋",Age=22},
                new Student(){StuId=1004,Sex="",StuName="黄豪",Age=16},
                new Student(){StuId=1005,Sex="",StuName="侯文倩",Age=19},
                new Student(){StuId=1006,Sex="",StuName="夏志雄",Age=28},
                new Student(){StuId=1007,Sex="",StuName="廖文勇",Age=20}
            };
            # endregion
            #region 分数集合
    
            List<Grade> gs = new List<Grade>()
            {
                new Grade(){ GId=1001,CoueseName="语文",Score=90,StuId=1001},
                new Grade(){ GId=1002,CoueseName="物理",Score=99,StuId=1001},
                new Grade(){ GId=1003,CoueseName="数学",Score=60,StuId=1001},
    
                new Grade(){ GId=1004,CoueseName="语文",Score=97,StuId=1003},
                new Grade(){ GId=1005,CoueseName="物理",Score=59,StuId=1003},
                new Grade(){ GId=1006,CoueseName="数学",Score=87,StuId=1003},
    
                new Grade(){ GId=1007,CoueseName="语文",Score=59,StuId=1004},
                new Grade(){ GId=1008,CoueseName="物理",Score=96,StuId=1004},
    
                new Grade(){ GId=1009,CoueseName="数学",Score=99,StuId=1006},
            };
            #endregion
            #region 排序
            //descending反序
            //ascending升序
            //****************************************************************************
            //OrderBy
    
            protected void Button2_Click(object sender, EventArgs e)
            {
                //例:绑定出性别为男的人
                var v = from s in stus
                        where s.Sex == ""
                        orderby s.StuId descending
                        select s;
                //select 姓名=stuName,sex 性别,age as 年龄 from student
                //取别名
                var v2 = from s in stus
                         where s.Age >= 18
                         select new { //将结果以匿名类的对象返回
                            编号=s.StuId,
                            姓名=s.StuName,
                            性别=s.Sex,
                            年龄=s.Age
                         };
    
                GridView1.DataSource = v2.ToList();
                GridView1.DataBind();
    
            }
            #endregion
            #region 子查询
            protected void Button3_Click(object sender, EventArgs e)
            {
                //子查询操作
                string[][] arr = new string[][]{
                  new string[] {"张秋蓉","夏志雄","廖琴"},
                  new string[] {"张三","李四"},
                  new string[] {"王五","夏六","刘七","胡八"}
                };
                //查询姓张的人
                //var v = from r in arr
                //        from a in r
                //        where a.StartsWith("张")
                //        select a;
                //SelectMany  可以取集合中子集里的元素,以一个集合返回
                //v = arr.SelectMany(s => s).Where(a =>a.StartsWith("张"));
                
                //foreach (var item in v)
                //{
                //    Response.Write("<br/>"+item);
                //}
                //查询出分数不及格的姓名  根据分数查出姓名
                #region  多表查询
                //select * from student,grade where student.stuid=grade.stuid and grade.score<60
                var v = from s in stus 
                        from g in gs
                        where g.Score < 60 && s.StuId == g.StuId
                        select s;
                #endregion
    
                #region 子查询
                var v1 = from g in gs//先查询分数
                         where g.Score < 60
                         from s in stus//查询姓名
                         where s.StuId == g.StuId//分数不及格对应的id和
                         select s;
                GridView1.DataSource = v1.ToList();
                GridView1.DataBind();
    
                #endregion
    
    
            }
            #endregion
    
    
            //连接查询  join
            protected void Button4_Click(object sender, EventArgs e)
            {
                //var v = from s in stus
                //        join g in gs
                //        on s.StuId equals g.StuId
                //        //where
                //        select new
                //        {
                //            学号=s.StuId,
                //            姓名=s.StuName,
                //            课程=g.CoueseName,
                //            分数=g.Score
                //        };
    
    
                //左链接---左边表为准,对应有边有多少条stuid,右边没有的以null填充,
                //先计算左边表的条数,在计算有边重复的条数,最后总和
    
                var v = from s in stus
                        join g in gs
                         on s.StuId equals g.StuId
                         into gx//将左与连接的右边数据放到一个集合中,如果右边没有左边对应的数据也会将一个空数据放到这个集合中
                         
                        from x in gx.DefaultIfEmpty()//当遍历集合中的空数据时也将null给x
                        select new
                        {
                            学号 = s.StuId,
                            姓名 = s.StuName,
                            课程 = (x!=null)?x.CoueseName:"",
                            分数 =(x!=null)?x.Score:0
                        };
                //Response.Write(v.Concat().ToString());
                GridView1.DataSource = v.ToList();
                GridView1.DataBind();
                
            }
            //分组查询
            protected void Button5_Click(object sender, EventArgs e)
            {
                //统计每门课程的参考人数、总分、平均分
                //select courseName,总分=sum(score),平均分=avg(score),人数=count(1) from grade froup by courseName having count(1)>2
                var v = from g in gs
                        group g by g.CoueseName
                            into gx
                            select gx;
                //IGrouping<string,Grade>;
                //IEnumerable<IGrouping<string,Grade>>;
                foreach (var item in v)
                {
                    Response.Write("<br/>组名:"+item.Key);
                    foreach (var t in item)
                    {
                        Response.Write("<br/>学号"+t.StuId+"分数:"+t.Score);
                    }
                    //绑定组信息
                    var vb = from g in gs
                             group g by g.CoueseName
                                 into gx
                                 select new { 课程 = gx.Key, 人数 = gx.Count(), 总分 = gx.Sum(a => a.Score) };
                    GridView1.DataSource = vb.ToList();
                    GridView1.DataBind();
                }
                
            }
            
            protected void Button6_Click(object sender, EventArgs e)
            {
                //查询出每个学生的总成绩,考试的课程数,平均成绩
    
                //学号  姓名  课程数  总分  平均成绩
                //1001  张三  3      270   90
                //1002  李四  2      170   8
                #region 多表查询和分组查询联合
                //var v = from g in gs
                //        group g by g.StuId
                //            into gx
                //            select new
                //            {
                //                学号 = gx.Key,
                //                课程数 = gx.Count(),
                //                总分 = gx.Sum(a => a.Score),
                //                平均 = gx.Average(a => a.Score)
                //            };
                //var vs = from s in stus
                //         join d in v
                //         on s.StuId equals d.学号
                //         select new
                //         {
                //             学号 = d.学号,
                //             姓名 = s.StuName,
                //             课程数 = d.课程数,
                //             总分 = d.总分,
                //             平均分 = d.平均
                //         };
                //GridView1.DataSource = vs;
                //GridView1.DataBind();
    
                #endregion 
    
                var v = from g in gs//查询成绩
                        group g by g.StuId//查询成绩表中的id
                            into gx//别名
                            from s in stus//查询名称
                            where gx.Key == s.StuId//查询名称id
                            select new
                            {
                                学号 = gx.Key,
                                姓名 = s.StuName,
                                课程数 = gx.Count(),
                                总分 = gx.Sum(a => a.Score),
                                平均 = gx.Average(a => a.Score)
                            };
                GridView1.DataSource = v.ToList();
                    GridView1.DataBind();
    
    
            }
    
            protected void Button7_Click(object sender, EventArgs e)
            {
                int pageIndex = Convert.ToInt32(TextBox1.Text);//1
                int pageSize = 3;//3条数据页
                var v = (from s in stus select s).Skip((pageIndex - 1) * pageSize).Take(pageSize);
                GridView1.DataSource = v.ToList();
                GridView1.DataBind();
    
            }
        }
    }

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LinqToXML.aspx.cs" Inherits="WebApplication1.LinqToXML" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            
            <asp:Button ID="Button1" runat="server" Text="创建XML文档" 
                onclick="Button1_Click" />
            
            <br />
            <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
                GridLines="None">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:TemplateField HeaderText="操作">
                        <ItemTemplate>
                            <asp:Button ID="Button7" runat="server" CommandArgument='<%# Eval("学号") %>' 
                                onclick="Button7_Click" Text="删除" />
                            <asp:Button ID="Button8" runat="server" CommandArgument='<%# Eval("学号") %>' 
                                onclick="Button8_Click" Text="编辑" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EditRowStyle BackColor="#2461BF" />
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#EFF3FB" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#F5F7FB" />
                <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                <SortedDescendingCellStyle BackColor="#E9EBEF" />
                <SortedDescendingHeaderStyle BackColor="#4870BE" />
            </asp:GridView>
            <asp:Button ID="Button2" runat="server" Text="绑定列表" onclick="Button2_Click" />
            <br />
            姓名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <br />
            性别:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <br />
            年龄:<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
            <br />
            <asp:Button ID="Button6" runat="server" onclick="Button6_Click" Text="新增" />
            <asp:Button ID="Button5" runat="server" Text="提交" onclick="Button5_Click" />
            <br />
            
        </div>
        </form>
    </body>
    </html>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml.Linq;
    
    namespace WebApplication1
    {
        public partial class LinqToXML : System.Web.UI.Page
        {
            string path = "";
            protected void Page_Load(object sender, EventArgs e)
            {
               
               
                path = Server.MapPath("/student.xml");
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                //创建XML文档
                XDocument doc = new XDocument(
                    new XElement("grade",
                        new XElement("student",
                            new XAttribute("stuid",Guid.NewGuid()),
                            new  XElement("name","汪昭贵"),
                            new XElement("sex",""),
                            new XElement("age","18")
                            ),
                            new XElement("student",
                            new XAttribute("stuid",Guid.NewGuid()),
                            new  XElement("name","豪哥"),
                            new XElement("sex",""),
                            new XElement("age","20")
                            ),
                             new XElement("student",
                            new XAttribute("stuid",Guid.NewGuid()),
                            new  XElement("name","胡佩"),
                            new XElement("sex",""),
                            new XElement("age","18")
                            )
                        )
    
                    );
    
                doc.Save(path);
                Response.Write("保存成功");
            }
    
            protected void Button2_Click(object sender, EventArgs e)
            {
                BindList();
    
            }
    
            private void BindList()
            {
                //绑定列表
                //1.加载xml文档
                XDocument doc = XDocument.Load(path);
                //2.查询所有student节点
                var v = from x in doc.Root.Descendants("student")//Descendants 取某个节点的子节点
                        //where x.Element("name").Value=="汪昭贵";
                        //where x.Attribute("stuid").Value="1001";
                        select new
                        {
                            学号 = x.Attribute("stuid").Value,
                            姓名 = x.Element("name").Value,
                            性别 = x.Element("sex").Value,
                            年龄 = x.Element("age").Value
                        };
    
                GridView1.DataSource = v.ToList();
                GridView1.DataBind();
            }
            //新增
            protected void Button6_Click(object sender, EventArgs e)
            {
                XDocument doc = XDocument.Load(path);
                var v= new XElement("student",
                    new XAttribute("stuid",Guid.NewGuid()),
                    new XElement("name",TextBox1.Text),
                    new XElement("sex",TextBox2.Text),
                    new XElement("age",TextBox3.Text)
                    );
                doc.Root.Add(v);
                doc.Save(path);
                BindList();
                   
            }
            //删除
            protected void Button7_Click(object sender, EventArgs e)
            {
                Button bt= sender as Button;
                string id = bt.CommandArgument;
                XDocument doc = XDocument.Load(path);
                var v = from t in doc.Descendants("student")
                        where t.Attribute("stuid").Value == id
                        select t;
                v.Remove();
                doc.Save(path);
                BindList();
            }
            //编辑
            protected void Button8_Click(object sender, EventArgs e)
            {
               Button bt= sender as Button;
               string id = bt.CommandArgument;
               ViewState["id"] = id;
               XDocument doc = XDocument.Load(path);
               var v = from t in doc.Descendants("student")
                       where t.Attribute("stuid").Value == id
                       select t;
               foreach (var item in v)
               {
                   TextBox1.Text = item.Element("name").Value;
                   TextBox2.Text = item.Element("sex").Value;
                   TextBox3.Text = item.Element("age").Value;
               }
    
    
    
            }
            //提交
            protected void Button5_Click(object sender, EventArgs e)
            {
               string id= ViewState["id"].ToString();
               
                XDocument doc = XDocument.Load(path);
                var v = from t in doc.Descendants("student")
                        where t.Attribute("stuid").Value == id
                        select t;
                foreach (var item in v)
                {
                    item.Element("name").Value = TextBox1.Text;
                    item.Element("sex").Value = TextBox2.Text;
                    item.Element("age").Value = TextBox3.Text;
                }
                doc.Save(path);
                BindList();
            }
        }
    }
  • 相关阅读:
    orale 命令行创建&删除数据库
    Oracle 之表分析
    电子商务分销历程
    乐宝分销,人人都是老板
    随手将TPaxScripter 3.0改成了支持Delphi 2009,Delphi 2010,Delphi Xe
    百丽强势布局B2C,20亿铺路改变其销售格局
    顺丰开通B2C商城,快递业欲抢多一寸电商蛋糕
    Exchange环境搭建心得
    c# 添加外部程序集相对引用问题
    Entity Framework Code First 学习
  • 原文地址:https://www.cnblogs.com/xiaz/p/5243102.html
Copyright © 2011-2022 走看看