目录
2.XElement类的SetAttributeValue()方法
对数组和集合进行操作时可以使用LINQtoObjects技术(一种新的处理集合的方法)。只需编写描述要检索的内容的声明性代码。LINQtoObjects直接使用LINQ查询IEnumerable或IEnumerable
- // LINQ to Objects
- // 使用LINQ操作数组和集合
-
- namespace _08
- {
- class Program
- {
- ///
- /// 定义一个数组1
- /// 使用LINQ技术从数组中查找及格范围内的数并存储于数组2
- /// 遍历输出数组2
- ///
- static void Main(String[] args)
- {
- if (args is null) //解除IDE0060
- {
- throw new ArgumentNullException(nameof(args));
- }
-
- int[] _Scores = { 45, 68, 80, 90, 75, 76, 32 };
- var _Score = from High_score in _Scores
- where High_score >= 60
- orderby High_score ascending
- select High_score;
-
- Console.WriteLine("及格的分数:");
-
- foreach(var sc in _Score) {
- Console.WriteLine(sc.ToString());
- }
- Console.ReadLine();
- }
- }
- }
- //运行结果:
- //及格的分数:
- //68
- //75
- //76
- //80
- //90
对DataSet数据集进行操作时可以使用LINQtoDataSet技术(LINQ to ADO.NET中的一种独立技术),使查询DataSet对象更加方便、快捷。
LINQtoDataSet技术中的常用方法:
AsEnumerable()方法可以将DataTable对象转换为EnumerableRowCollection
- public static EnumerableRowCollection
AsEnumerable(this DataTable source) - ☑ source:可枚举的源DataTable。
- ☑ 返回值:一个IEnumerable
对象,其泛型参数T为DataRow。
CopyToDataTable()方法用来将IEnumerable
- public static DataTable CopyToDataTable<T>(this IEnumerable
source )where T:DataRow - ☑ source:源IEnumerable
序列。 - ☑ 返回值:一个DataTable,其中包含作为DataRow对象的类型的输入序列。
AsDataView()方法用来创建并返回支持LINQ的DataView对象:
- public static DataView AsDataView<T>(this EnumerableRowCollection
source )where T:DataRow - ☑ source:从中创建支持LINQ的DataView的源LINQ to DataSet查询。
- ☑ 返回值:支持LINQ的DataView对象
Take()方法用来从序列的开头返回指定数量的连续元素:
- public static IEnumerable<TSource>Take<TSource>(this IEnumerable
source,int count ) - ☑ source:要从其返回元素的序列。
- ☑ count:要返回的元素数量。
- ☑ 返回值:一个IEnumerable
,包含输入序列开头的指定数量的元素。
Sum()方法用来计算数值序列之和:
- public static decimal Sum(this IEnumerable<decimal>source)
- ☑ source:一个要计算和的Decimal值序列。
- ☑ 返回值:序列值之和
上面介绍的几种方法都有多种重载形式。
使用了LINQ to DataSet技术的AsEnumerable() 方法和CopyToDataTable()方法。
- //Form1.cs
- // LINQ to DataSet
- // 使用LINQ操作DataSet数据集
- // 使用了LINQ to DataSet技术的AsEnumerable() 方法和CopyToDataTable()方法
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Windows.Forms;
-
- namespace _09
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- public string _strCon;
-
- ///
- /// LINQ to DataSet流程:
- /// SqlConnection实例化
- /// SqlDataAdapter实例化
- /// DataSet实例化
- /// 使用LINQ从数据集中查询所有数据
- /// 将查询结果生成DataTable,并作为dataGridView1的数据源
- ///
- private void Form1_Load(object sender, EventArgs e)
- {
- dataGridView1.Dock = DockStyle.Fill;
- _strCon = "Data Source=DESKTOP-3LV13FS;Initial Catalog=db_CSharp;Integrated Security=True"; //定义数据库连接字符串
-
- SqlConnection sqlcon = new SqlConnection(_strCon); //实例化数据库连接对象
- SqlDataAdapter sqlda = new SqlDataAdapter("select * from tb_Salary", sqlcon); //实例化数据库桥接器对象
- DataSet myds = new DataSet(); //实例化数据集对象
- sqlda.Fill(myds, "tb_Salary"); //填充DataSet数据集
- var Query = from salary in myds.Tables["tb_Salary"].AsEnumerable() //使用LINQ从数据集中查询所有数据
- select salary;
- DataTable myDTable = Query.CopyToDataTable
(); //将查询结果转化为DataTable对象 - dataGridView1.DataSource = myDTable; //显示查询到的数据集中的信息
- }
- }
- }

对XML文件进行操作时可以使用LINQtoXML技术(LINQ技术中的一种,提供了修改文档对象模型的内存文档,并支持LINQ查询表达式等功能)。
Xelement类表示一个XML元素,其Load()方法用来从文件加载Xelement:
- public static XElement Load(string url)
- ☑ url:一个url字符串,用来引用要加载到新XElement中的文件。
- ☑ 返回值:一个包含指定文件内容的XElement。
SetAttributeValue()方法用来设置属性的值、添加属性或移除属性。
- public void SetAttributeValue(XName name,Object value)
- ☑ name:一个XName,其中包含要更改的属性的名称。
- ☑ value:分配给属性的值。如果该值为null,则移除该属性;否则,会将值转换为其字符串表示形式,并分配给该属性的Value属性。
Add()方法用来将指定的内容添加为此XContainer的子级。
- public void Add(Object content)
- content表示要添加的包含简单内容的对象或内容对象集合。
ReplaceNodes()方法用来使用指定的内容替换此文档或元素的子节点。
- public void ReplaceNodes(Object content)
- content表示一个用于替换子节点的包含简单内容的对象或内容对象集合。
Save()方法用来序列化此元素的基础XML树,可以将输出保存到文件、XmlTextWriter、TextWriter或XmlWriter。
- public void Save(string fileName)
- fileName是一个包含文件名称的字符串。
XDocument类表示XML文档,其Save()方法用来将此XDocument序列化为文件、TextWriter或XmlWriter。
- public void Save(string fileName)
- fileName是一个包含文件名称的字符串。
XDeclaration类表示一个XML声明。
- public XDeclaration(string version,string encoding,string standalone)
- ☑ version:XML的版本,通常为“1.0”。
- ☑ encoding:XML文档的编码。
- ☑ standalone:包含yes或no的字符串,用来指定XML是独立的还是需要解析外部实体。
使用LINQtoXML技术中的类时,需要添加System.Linq.Xml命名空间。
使用了XElement类的Load()方法、XElement类的Add()方法、XElement类的Save()方法。使用了Xnode类的Remove()方法。
- //Form1.cs
- // LINQ to XML
- // 使用LINQ操作XML
- // 使用了XElement类的Load()方法、XElement类的Add()方法、XElement类的Save()方法
- // 使用了Xnode类的Remove()方法
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- using static System.Windows.Forms.VisualStyles.VisualStyleElement;
- using System.Xml.Linq;
-
- namespace _10
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- public static string _strPath = "Employee.xml"; //文件放在DEBUG根目录
- public static string _strID = "";
-
- ///
- /// 初始化Form1
- /// 调用自定义方法加载XML文件
- ///
- private void Form1_Load(object sender, EventArgs e)
- {
- label1.Text = "姓名:";
- label2.Text = "薪水:";
- label3.Text = "性别:";
- button1.Text = "添加";
- button2.Text = "修改";
- button3.Text = "删除";
- groupBox1.Text = "LINQtoXML操作XML文件";
- comboBox1.Items.AddRange(new object[] { "男", "女" });
-
- button1.Size = new Size(40, 21);
- button2.Size = new Size(40, 21);
- button3.Size = new Size(40, 21);
- comboBox1.Size = new Size(40, 21);
- textBox1.Size = new Size(80, 21);
- textBox2.Size = new Size(60, 21);
-
- GetXmlInfo(); //窗体加载时加载XML文件
- }
-
- #region 将XML文件内容绑定到DataGridView控件
- ///
- /// 将XML文件内容绑定到DataGridView控件
- /// 定义一个数据集合并利用其ReadXml()方法绑定XML文件
- /// dataGridView1的数据源=数据集合
- ///
- private void GetXmlInfo()
- {
- DataSet myds = new DataSet();
- myds.ReadXml(_strPath);
- dataGridView1.DataSource = myds.Tables[0];
- }
- #endregion
-
- ///
- /// 添加
- /// 使用了XElement类的Load()方法、XElement类的Add()方法、XElement类的Save()方法
- ///
- private void Button1_Click(object sender, EventArgs e)
- {
- XElement xe = XElement.Load(_strPath);
- IEnumerable
elements1 = from element in xe.Elements("People") - select element;
- //生成新的编号
- string str = (Convert.ToInt32(elements1.Max(element => element.Attribute("ID").Value)) + 1).ToString("000");
- XElement people = new XElement(
- "People", new XAttribute("ID", str),
- new XElement("Name", textBox1.Text),
- new XElement("Sex", comboBox1.Text),
- new XElement("Salary", textBox2.Text)
- );
- xe.Add(people);
- xe.Save(_strPath);
- GetXmlInfo();
- }
-
- ///
- /// 修改
- /// 使用了XElement类的Load()方法、XElement类的Save()方法
- ///
- private void Button2_Click(object sender, EventArgs e)
- {
- if (_strID != "")
- {
- XElement xe = XElement.Load(_strPath);
- IEnumerable
elements = from element in xe.Elements("People") - where element.Attribute("ID").Value == _strID
- select element;
- if (elements.Count() > 0)
- {
- XElement newXE = elements.First();
- newXE.SetAttributeValue("ID", _strID);
- newXE.ReplaceNodes(
- new XElement("Name", textBox1.Text),
- new XElement("Sex", comboBox1.Text),
- new XElement("Salary", textBox2.Text)
- );
- }
- xe.Save(_strPath);
- }
- GetXmlInfo();
- }
-
- ///
- /// 删除
- /// 使用了XElement类的Load()方法、XElement类的Save()方法、Xnode类的Remove()方法
- ///
- private void Button3_Click(object sender, EventArgs e)
- {
- if (_strID != "")
- {
- XElement xe = XElement.Load(_strPath);
- IEnumerable
elements = from element in xe.Elements("People") - where element.Attribute("ID").Value == _strID
- select element;
- if (elements.Count() > 0)
- elements.First().Remove();
- xe.Save(_strPath);
- }
- GetXmlInfo();
- }
-
- ///
- /// 显示鼠标选中XML点的详细信息,并赋值给文本框
- /// 使用了XElement类的Load()方法
- ///
- private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
- {
- _strID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
- XElement xe = XElement.Load(_strPath);
- IEnumerable
elements = from SelectedInfo in xe.Elements("People") - where SelectedInfo.Attribute("ID").Value == _strID
- select SelectedInfo;
- foreach (XElement element in elements)
- {
- textBox1.Text = element.Element("Name").Value;
- textBox2.Text = element.Element("Salary").Value;
- comboBox1.SelectedItem = element.Element("Sex").Value;
- }
- }
- }
- }
原表和增加、修改、删除后的表

