当前位置: 首页 > news >正文

C#中LINQtoObjects、LINQtoDataSet和LINQtoXML

目录

一、使用LINQ操作数组和集合

二、使用LINQ操作DataSet数据集

1.AsEnumerable()方法

2.CopyToDataTable()方法

3.AsDataView()方法

4.Take()方法

5.Sum()方法

6.示例

(1)源码

(2)生成效果

三、使用LINQ操作XML

1.XElement类的Load()方法

2.XElement类的SetAttributeValue()方法

3.XElement类的Add()方法

4.XElement类的ReplaceNodes()方法

5.XElement类的Save()方法

6.XDocument类的Save()方法

7.XDeclaration类

8.示例

(1)源码

(2)生成效果


一、使用LINQ操作数组和集合

        对数组和集合进行操作时可以使用LINQtoObjects技术(一种新的处理集合的方法)。只需编写描述要检索的内容的声明性代码。LINQtoObjects直接使用LINQ查询IEnumerable或IEnumerable<T>集合,使用LINQ能够查询任何可枚举的集合,例如数组、泛型列表等。

// LINQ to Objects
// 使用LINQ操作数组和集合namespace _08
{class Program{/// <summary>/// 定义一个数组1/// 使用LINQ技术从数组中查找及格范围内的数并存储于数组2/// 遍历输出数组2/// </summary>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 _Scoreswhere High_score >= 60orderby High_score ascending  select High_score;Console.WriteLine("及格的分数:");foreach(var sc in _Score) { Console.WriteLine(sc.ToString());}Console.ReadLine();}}
}
//运行结果:
//及格的分数:
//68
//75
//76
//80
//90

二、使用LINQ操作DataSet数据集

        对DataSet数据集进行操作时可以使用LINQtoDataSet技术(LINQ to ADO.NET中的一种独立技术),使查询DataSet对象更加方便、快捷。

        LINQtoDataSet技术中的常用方法:

1.AsEnumerable()方法

        AsEnumerable()方法可以将DataTable对象转换为EnumerableRowCollection <DataRow>对象:

public static EnumerableRowCollection<DataRow>AsEnumerable(this DataTable source)
☑ source:可枚举的源DataTable。
☑ 返回值:一个IEnumerable<T>对象,其泛型参数T为DataRow。

2.CopyToDataTable()方法

        CopyToDataTable()方法用来将IEnumerable<T>对象中的数据赋值到DataTable对象中:

public static DataTable CopyToDataTable<T>(this IEnumerable<T>source)where T:DataRow
☑ source:源IEnumerable<T>序列。
☑ 返回值:一个DataTable,其中包含作为DataRow对象的类型的输入序列。

3.AsDataView()方法

        AsDataView()方法用来创建并返回支持LINQ的DataView对象:

public static DataView AsDataView<T>(this EnumerableRowCollection<T>source)where T:DataRow 
☑ source:从中创建支持LINQ的DataView的源LINQ to DataSet查询。
☑ 返回值:支持LINQ的DataView对象

4.Take()方法

        Take()方法用来从序列的开头返回指定数量的连续元素:

public static IEnumerable<TSource>Take<TSource>(this IEnumerable<TSource>source,int count)
☑ source:要从其返回元素的序列。
☑ count:要返回的元素数量。
☑ 返回值:一个IEnumerable<T>,包含输入序列开头的指定数量的元素。

5.Sum()方法

        Sum()方法用来计算数值序列之和:

public static decimal Sum(this IEnumerable<decimal>source)
☑ source:一个要计算和的Decimal值序列。
☑ 返回值:序列值之和

        上面介绍的几种方法都有多种重载形式。

6.示例

        使用了LINQ to DataSet技术的AsEnumerable() 方法和CopyToDataTable()方法。

(1)源码

//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;/// <summary>/// LINQ to DataSet流程:/// SqlConnection实例化/// SqlDataAdapter实例化/// DataSet实例化/// 使用LINQ从数据集中查询所有数据/// 将查询结果生成DataTable,并作为dataGridView1的数据源/// </summary>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<DataRow>();           //将查询结果转化为DataTable对象dataGridView1.DataSource = myDTable;                                            //显示查询到的数据集中的信息}}   
}

(2)生成效果

三、使用LINQ操作XML

        对XML文件进行操作时可以使用LINQtoXML技术(LINQ技术中的一种,提供了修改文档对象模型的内存文档,并支持LINQ查询表达式等功能)。

1.XElement类的Load()方法

        Xelement类表示一个XML元素,其Load()方法用来从文件加载Xelement:

public static XElement Load(string url) 
☑ url:一个url字符串,用来引用要加载到新XElement中的文件。
☑ 返回值:一个包含指定文件内容的XElement。

2.XElement类的SetAttributeValue()方法

        SetAttributeValue()方法用来设置属性的值、添加属性或移除属性。

public void SetAttributeValue(XName name,Object value)
☑ name:一个XName,其中包含要更改的属性的名称。
☑ value:分配给属性的值。如果该值为null,则移除该属性;否则,会将值转换为其字符串表示形式,并分配给该属性的Value属性。

3.XElement类的Add()方法

        Add()方法用来将指定的内容添加为此XContainer的子级。

public void Add(Object content) 
content表示要添加的包含简单内容的对象或内容对象集合。

4.XElement类的ReplaceNodes()方法

        ReplaceNodes()方法用来使用指定的内容替换此文档或元素的子节点。

public void ReplaceNodes(Object content)
content表示一个用于替换子节点的包含简单内容的对象或内容对象集合。

5.XElement类的Save()方法

        Save()方法用来序列化此元素的基础XML树,可以将输出保存到文件、XmlTextWriter、TextWriter或XmlWriter。

public void Save(string fileName) 
fileName是一个包含文件名称的字符串。 

6.XDocument类的Save()方法

        XDocument类表示XML文档,其Save()方法用来将此XDocument序列化为文件、TextWriter或XmlWriter。

public void Save(string fileName) 
fileName是一个包含文件名称的字符串。

7.XDeclaration类

        XDeclaration类表示一个XML声明。

public XDeclaration(string version,string encoding,string standalone)
☑ version:XML的版本,通常为“1.0”。
☑ encoding:XML文档的编码。
☑ standalone:包含yes或no的字符串,用来指定XML是独立的还是需要解析外部实体。

        使用LINQtoXML技术中的类时,需要添加System.Linq.Xml命名空间。

8.示例

        使用了XElement类的Load()方法、XElement类的Add()方法、XElement类的Save()方法。使用了Xnode类的Remove()方法。

(1)源码

//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 = "";/// <summary>/// 初始化Form1/// 调用自定义方法加载XML文件/// </summary>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控件/// <summary>/// 将XML文件内容绑定到DataGridView控件/// 定义一个数据集合并利用其ReadXml()方法绑定XML文件///  dataGridView1的数据源=数据集合/// </summary>private void GetXmlInfo(){DataSet myds = new DataSet();myds.ReadXml(_strPath);dataGridView1.DataSource = myds.Tables[0];}#endregion/// <summary>/// 添加/// 使用了XElement类的Load()方法、XElement类的Add()方法、XElement类的Save()方法/// </summary>private void Button1_Click(object sender, EventArgs e){XElement xe = XElement.Load(_strPath);IEnumerable<XElement> 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();}/// <summary>/// 修改/// 使用了XElement类的Load()方法、XElement类的Save()方法/// </summary>private void Button2_Click(object sender, EventArgs e){if (_strID != ""){XElement xe = XElement.Load(_strPath);IEnumerable<XElement> elements = from element in xe.Elements("People")where element.Attribute("ID").Value == _strIDselect 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();}/// <summary>/// 删除/// 使用了XElement类的Load()方法、XElement类的Save()方法、Xnode类的Remove()方法/// </summary>private void Button3_Click(object sender, EventArgs e){if (_strID != ""){XElement xe = XElement.Load(_strPath);IEnumerable<XElement> elements = from element in xe.Elements("People")where element.Attribute("ID").Value == _strIDselect element;if (elements.Count() > 0)elements.First().Remove();xe.Save(_strPath);}GetXmlInfo();}/// <summary>/// 显示鼠标选中XML点的详细信息,并赋值给文本框/// 使用了XElement类的Load()方法/// </summary>private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e){_strID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();XElement xe = XElement.Load(_strPath);IEnumerable<XElement> elements = from SelectedInfo in xe.Elements("People")where SelectedInfo.Attribute("ID").Value == _strIDselect SelectedInfo;foreach (XElement element in elements){textBox1.Text = element.Element("Name").Value;               textBox2.Text = element.Element("Salary").Value;comboBox1.SelectedItem = element.Element("Sex").Value;}}}
}

(2)生成效果

         原表和增加、修改、删除后的表

 

 

http://www.lryc.cn/news/217487.html

相关文章:

  • k8s中 RBAC中,clusterrole,serviceaccount , rolebinding 是什么关系谁先谁后
  • 什么是文件安全
  • maven的settings.xml和pom.xml配置文件详解
  • YB2503HV 100V 3A SOP8内置MOS 高效率降压IC(昱灿)
  • Redis安装Linux
  • PCL点云处理(007)-Ransac
  • 有方N58 HTTP POST 请求连接 TDengine
  • 基于Python+Pygame实现一个滑雪小游戏
  • 【限制输入框值类型】自定义指令el-input输入类型限制,vue和html两个版本
  • 对一个金融风控测额公式的理解(1)
  • 【GEE】2、探索数据集
  • 开发一款直播弹幕游戏需要多少钱?
  • STM32F103C8T6第一天:认识STM32 标准库与HAL库 GPIO口 推挽输出与开漏输出
  • selenium元素定位 —— 提高篇 CSS定位元素
  • 隔离和非隔离电源的区别
  • C语言自定义数据类型
  • SoftwareTest5 - 你就只知道功能测试吗 ?
  • Uniapp 中,能够同时兼容H5、web、app、微信小程序的引入高德地图的语法格式
  • 基于nodejs+vue网上鲜花销售系统
  • stm32 ETH
  • 【深度学习基础】Pytorch框架CV开发(2)实战篇
  • C语言--输出1-100以内同时能被3和5整除的数
  • Linux--jdk、tomcat、环境配置,mysql安装、后端项目搭建
  • NOIP2023模拟10联测31 迷路
  • React Query + Redux toolkit 封装异步请求
  • CSS基础知识点速览
  • Windows 时间服务配置和配置工具
  • cmake find_package、引用GDAL 初步学习
  • 紫光同创FPGA编写的8画面分割器演示
  • openLayers--绘制多边形、获取视图的中心点、获取当前地图等级、设置地图等级