161-order-by-in-linq-query-and-linq-query-on-xml-document-c

LINQ in C# stands for Language Integrated Query. It is brilliant programming concept implemented in C# programming language to virtualizes underlying data source. This means, that for example we can apply linq query on XML document in C# as easy as we would implement SQL query on the database. In this tutorial, we will use “orderby” clause to sort data from plain text file. Using order by in Linq query C# we will sort persons by name, then by surname. In plain text file there are raw data with person’s name, surname and phone number delimited with comma. Since we want to structure this raw data we can apply simple algorithm:

Open plain text → Convert data to XML → Apply Linq query on XML data

In order to convert data to XML, it is more convenient to read data from txt file line by line. We also need separate string arrays for person name, surname and phone number respectively.

string[] all_lines = File.ReadAllLines(str_file_to_open);
string[] names = new string[all_lines.Length];
string[] surnames = new string[all_lines.Length];
string[] tel_no = new string[all_lines.Length];
string str_parse;

Then we can create XML file settings.
XmlWriterSettings xml_WS = new XmlWriterSettings();
xml_WS.Indent = true;

We can automatically crate file with the same file name as txt file, but with xml extension.

string str_save_xml;
str_save_xml = str_file_to_open.Substring(0, str_file_to_open.Length – 3);
str_save_xml += “xml”;
this.Text = str_save_xml;

After preparing file name, we can create XML file

XmlWriter xml_Wr = XmlWriter.Create(str_save_xml, xml_WS);
xml_Wr.WriteStartDocument();
xml_Wr.WriteComment(“Just a comment”);
xml_Wr.WriteStartElement(“People”);
xml_Wr.WriteAttributeString(“xsi”, “noNamespaceSchemaLocation”, “http://www.w3.org/2001/XMLSchema-instance”, “http://www.yoursite.com/xml/”);

Then we read data line by line in for loop
for (int i = 0; i < all_lines.Length; i++ )
{

str_parse = all_lines[i];

Read line we parse

string[] separated = str_parse.Split(‘,’);
Since there are three columns in row we can store name, surname and phone number respectively:
names[i] = separated[0];
surnames[i] = separated[1];
tel_no[i] = separated[2];

Now we can form XML node:

xml_Wr.WriteStartElement(“Person”);
xml_Wr.WriteStartElement(“Name”);
xml_Wr.WriteString(names[i]);
xml_Wr.WriteEndElement();
xml_Wr.WriteStartElement(“Surname”);
xml_Wr.WriteString(surnames[i]);
xml_Wr.WriteEndElement();
xml_Wr.WriteStartElement(“Phone”);
xml_Wr.WriteString(tel_no[i]);
xml_Wr.WriteEndElement();

xml_Wr.WriteEndElement(); // Closing “Person”

}

Then we close the document.

xml_Wr.WriteEndElement(); // Closing “People”
xml_Wr.WriteEndDocument();
xml_Wr.Flush();
xml_Wr.Close();

Now we can start to use XML document for Linq.

XDocument xdoc = XDocument.Load(str_save_xml);

Since we want to order first by name and then by surname, order by in linq query C# in this example looks like this:

var result = from c in xdoc.Descendants(“Person”)

orderby c.Element(“Surname”).Value
orderby c.Element(“Name”).Value
select c.Element(“Name”).Value + ” ” +
c.Element(“Surname”).Value + ” ” +
c.Element(“Phone”).Value;

From bottom-up we first order by name, then by surname in order to have data sorted first by name then by surname. For this purpose we need to use .Value property. Then we can use foreach loop to collect query result.

string str_write;
str_write = “”;
foreach (string employee in result)
{

str_write += employee.ToString() + System.Environment.NewLine;

}
textBox1.Text = str_write;

Additional namespaces used for this tutorial are:
using System.IO;
using System.Xml;
using System.Xml.Linq;

Whole code is:

if( openFileDialog1.ShowDialog() == DialogResult.OK)
{

string str_file_to_open = openFileDialog1.FileName;
StreamReader srRead = new StreamReader(str_file_to_open);
string[] all_lines = File.ReadAllLines(str_file_to_open);
string[] names = new string[all_lines.Length];
string[] surnames = new string[all_lines.Length];
string[] tel_no = new string[all_lines.Length];
string str_parse;

XmlWriterSettings xml_WS = new XmlWriterSettings();
xml_WS.Indent = true;
string str_save_xml;
str_save_xml = str_file_to_open.Substring(0, str_file_to_open.Length – 3);
str_save_xml += “xml”;
this.Text = str_save_xml;
XmlWriter xml_Wr = XmlWriter.Create(str_save_xml, xml_WS);
xml_Wr.WriteStartDocument();
xml_Wr.WriteComment(“Just a comment”);
xml_Wr.WriteStartElement(“People”);
xml_Wr.WriteAttributeString(“xsi”, “noNamespaceSchemaLocation”, “http://www.w3.org/2001/XMLSchema-instance”, “http://www.yoursite.com/xml/”);

for (int i = 0; i < all_lines.Length; i++ )
{

str_parse = all_lines[i];
string[] separated = str_parse.Split(‘,’);
names[i] = separated[0];
surnames[i] = separated[1];
tel_no[i] = separated[2];
xml_Wr.WriteStartElement(“Person”);
xml_Wr.WriteStartElement(“Name”);
xml_Wr.WriteString(names[i]);
xml_Wr.WriteEndElement();
xml_Wr.WriteStartElement(“Surname”);
xml_Wr.WriteString(surnames[i]);
xml_Wr.WriteEndElement();
xml_Wr.WriteStartElement(“Phone”);
xml_Wr.WriteString(tel_no[i]);
xml_Wr.WriteEndElement();
xml_Wr.WriteEndElement(); // Closing “Person”

}
xml_Wr.WriteEndElement(); // Closing “People”
xml_Wr.WriteEndDocument();
xml_Wr.Flush();
xml_Wr.Close();
textBox1.Text = srRead.ReadToEnd();
srRead.Close();

XDocument xdoc = XDocument.Load(str_save_xml);

var result = from c in xdoc.Descendants(“Person”)
orderby c.Element(“Surname”).Value
orderby c.Element(“Name”).Value
select c.Element(“Name”).Value + ” ” +
c.Element(“Surname”).Value + ” ” +
c.Element(“Phone”).Value;

string str_write;
str_write = “”;
foreach (string employee in result)
{

str_write += employee.ToString() + System.Environment.NewLine;

}
textBox1.Text = str_write;.

}

External links:

Order by in Linq Query C# in Stackoverflow
Order by in Linq Query C# in dotnetperls
Linq Query on XML Document C# in intertech
Linq Query on XML Document C# in java2s

Posted in c-sharp-code-examples

Leave a Reply

Your email address will not be published. Required fields are marked *

*