LINQtoObjects, LINQtoDataSet and LINQtoXML in C#

Table of Contents

1. Use LINQ to operate arrays and collections

2. Use LINQ to operate DataSet data set

1.AsEnumerable() method

2.CopyToDataTable() method

3.AsDataView() method

4.Take() method

5.Sum() method

6.Example

(1) Source code

(2) Generate effect

3. Use LINQ to operate XML

1.Load() method of XElement class

2.SetAttributeValue() method of XElement class

3.Add() method of XElement class

4.ReplaceNodes() method of XElement class

5.Save() method of XElement class

6.Save() method of XDocument class

7.XDeclaration class

8.Example

(1) Source code

(2) Generate effect


1. Use LINQ to operate arrays and collections

You can use LINQtoObjects technology (a new method of processing collections) when operating on arrays and collections. Just write declarative code that describes what you want to retrieve. LINQtoObjects directly uses LINQ to query IEnumerable or IEnumerable collections. Using LINQ, you can query any enumerable collection, such as arrays, generic lists, etc.

// LINQ to Objects
// Use LINQ to operate on arrays and collections

namespace_08
{
    class Program
    {
        /// <summary>
        /// Define an array 1
        /// Use LINQ technology to find numbers within the passing range from the array and store them in array 2
        /// Traverse output array 2
        /// </summary>
        static void Main(String[] args)
        {
            if (args is null) //Remove 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("Passing score:");

            foreach(var sc in _Score) {
                Console.WriteLine(sc.ToString());
            }
            Console.ReadLine();
        }
    }
}
//operation result:
//Passing score:
//68
//75
//76
//80
//90

2. Use LINQ to operate DataSet data set

When operating the DataSet data set, you can use LINQtoDataSet technology (an independent technology in LINQ to ADO.NET) to make querying the DataSet object more convenient and faster.

Common methods in LINQtoDataSet technology:

1.AsEnumerable() method

The AsEnumerable() method can convert a DataTable object into an EnumerableRowCollection object:

public static EnumerableRowCollection<DataRow>AsEnumerable(this DataTable source)
? source: enumerable source DataTable.
? Return value: an IEnumerable<T> object, whose generic parameter T is DataRow. 

2.CopyToDataTable() method

The CopyToDataTable() method is used to assign the data in the IEnumerable object to the DataTable object:

public static DataTable CopyToDataTable<T>(this IEnumerable<T>source)where T:DataRow
? source: source IEnumerable<T> sequence.
? Return value: A DataTable containing the input sequence as a type of DataRow object. 

3.AsDataView() method

The AsDataView() method is used to create and return a LINQ-enabled DataView object:

public static DataView AsDataView<T>(this EnumerableRowCollection<T>source)where T:DataRow
? source: The source LINQ to DataSet query from which the LINQ-enabled DataView was created.
?Return value: DataView object that supports LINQ

4.Take() method

The Take() method is used to return a specified number of consecutive elements from the beginning of the sequence:

public static IEnumerable<TSource>Take<TSource>(this IEnumerable<TSource>source,int count)
? source: The sequence from which elements are to be returned.
? count: The number of elements to return.
? Return value: an IEnumerable<T> containing the specified number of elements from the beginning of the input sequence. 

5.Sum() method

The Sum() method is used to calculate the sum of a sequence of numbers:

public static decimal Sum(this IEnumerable<decimal>source)
? source: a sequence of Decimal values to be summed.
?Return value: sum of sequence values

Several methods introduced above have multiple overloaded forms.

6.Example

The AsEnumerable() method and CopyToDataTable() method of LINQ to DataSet technology are used.

(1) Source code

//Form1.cs
// LINQ to DataSet
// Use LINQ to operate the DataSet data set
//Using the AsEnumerable() method and CopyToDataTable() method of LINQ to DataSet technology
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 process:
        /// SqlConnection instantiation
        /// SqlDataAdapter instantiation
        /// DataSet instantiation
        /// Use LINQ to query all data from the dataset
        /// Generate a DataTable from the query results and use it as the data source of 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"; //Define database connection string
           
            SqlConnection sqlcon = new SqlConnection(_strCon); //Instantiate the database connection object
            SqlDataAdapter sqlda = new SqlDataAdapter("select * from tb_Salary", sqlcon); //Instantiate the database bridge object
            DataSet myds = new DataSet(); //Instantiate the data set object
            sqlda.Fill(myds, "tb_Salary"); //Fill the DataSet data set
            var Query = from salary in myds.Tables["tb_Salary"].AsEnumerable() //Use LINQ to query all data from the data set
                        select salary;
            DataTable myDTable = Query.CopyToDataTable<DataRow>(); //Convert query results into DataTable objects
            dataGridView1.DataSource = myDTable; //Display the information in the queried data set
        }
    }
}

(2) Generate effect

3. Use LINQOperate XML

When operating XML files, you can use LINQtoXML technology (a type of LINQ technology that provides in-memory documents that modify the document object model and supports functions such as LINQ query expressions).

1.Load() method of XElement class

The Xelement class represents an XML element, and its Load() method is used to load Xelement from a file:

public static XElement Load(string url)
? url: A url string used to reference the file to be loaded into the new XElement.
? Return value: an XElement containing the contents of the specified file. 

2.SetAttributeValue() method of XElement class

The SetAttributeValue() method is used to set the value of an attribute, add an attribute, or remove an attribute.

public void SetAttributeValue(XName name,Object value)
? name: An XName that contains the name of the property to be changed.
? value: The value assigned to the attribute. If the value is null, the property is removed; otherwise, the value is converted to its string representation and assigned to the property's Value property. 

3.Add() method of XElement class

The Add() method is used to add the specified content to the child of this XContainer.

public void Add(Object content)
content represents an object or collection of content objects containing simple content to be added. 

4.ReplaceNodes() method of class XElement

The ReplaceNodes() method is used to replace the child nodes of this document or element with the specified content.

public void ReplaceNodes(Object content)
content represents an object or collection of content objects containing simple content used to replace child nodes. 

5.Save() method of class XElement

The Save() method is used to serialize the underlying XML tree of this element, and can save the output to a file, XmlTextWriter, TextWriter, or XmlWriter.

public void Save(string fileName)
fileName is a string containing the name of the file. 

6.Save() method of XDocument class

The XDocument class represents an XML document, and its Save() method is used to serialize this XDocument into a file, TextWriter or XmlWriter.

public void Save(string fileName)
fileName is a string containing the name of the file. 

7.XDeclaration class

The XDeclaration class represents an XML declaration.

public XDeclaration(string version,string encoding,string standalone)
? version: XML version, usually "1.0".
? encoding: encoding of XML document.
? standalone: A string containing yes or no, used to specify whether the XML is independent or requires parsing of external entities. 

When using classes in LINQtoXML technology, you need to add the System.Linq.Xml namespace.

8.Example

The Load() method of the XElement class, the Add() method of the XElement class, and the Save() method of the XElement class are used. The Remove() method of the Xnode class is used.

(1) Source code

//Form1.cs
// LINQ to XML
// Use LINQ to manipulate XML
//Used the Load() method of the XElement class, the Add() method of the XElement class, and the Save() method of the XElement class
//Used the Remove() method of the Xnode class
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"; //The file is placed in the DEBUG root directory
        public static string _strID = "";

        /// <summary>
        /// Initialize Form1
        /// Call custom method to load XML file
        /// </summary>
        private void Form1_Load(object sender, EventArgs e)
        {
            label1.Text = "Name:";
            label2.Text = "Salary:";
            label3.Text = "Gender:";
            button1.Text = "Add";
            button2.Text = "Modify";
            button3.Text = "Delete";
            groupBox1.Text = "LINQtoXML operates XML files";
            comboBox1.Items.AddRange(new object[] { "male", "female" });

            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(); //Load the XML file when the form loads
        }

        #region Bind XML file content to DataGridView control
        /// <summary>
        /// Bind the XML file content to the DataGridView control
        /// Define a data set and use its ReadXml() method to bind the XML file
        /// Data source of dataGridView1 = data collection
        /// </summary>
        private void GetXmlInfo()
        {
            DataSet myds = new DataSet();
            myds.ReadXml(_strPath);
            dataGridView1.DataSource = myds.Tables[0];
        }
        #endregion

        /// <summary>
        /// Add to
        /// Uses the Load() method of the XElement class, the Add() method of the XElement class, and the Save() method of the XElement class
        /// </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;
            //Generate new number
            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>
        /// Revise
        /// Uses the Load() method of the XElement class and the Save() method of the XElement class
        /// </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 == _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();
        }

        /// <summary>
        /// delete
        /// Uses the Load() method of the XElement class, the Save() method of the XElement class, and the Remove() method of the Xnode class
        /// </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 == _strID
                                                 select element;
                if (elements.Count() > 0)
                    elements.First().Remove();
                xe.Save(_strPath);
            }
            GetXmlInfo();
        }

        /// <summary>
        /// Display the detailed information of the XML point selected by the mouse and assign it to the text box
        /// Used the Load() method of the XElement class
        /// </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 == _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;
            }
        }
    }
}

(2) Generate effect

The original table and the added, modified, or deleted table