Caveman's Blog

My commitment to learning.

Archive for the ‘Linq’ Category

Linq: Contains operator

leave a comment »


The Contains method determines weather a sequence contains a specified element by using the default equality comparer. The following code illustrated a how “contains” and “not contains” operations can be implemented to filter a list of objects. In this sample code we filter the objects on the “name” property, the code for generating the collection class can be obtained from my previous post:

//Filter by "007" containing as a part of the employee list
var sortedEmployees = EmployeeList.Where(i => i.name.Contains("007")).ToList();

//Filter by "007" NOT containing as a part of the employee list
sortedEmployees = EmployeeList.Where(i => !i.name.Contains("007")).ToList();

The contains method also has an overloaded method, which can take a custom comparer as an argument. The custom comparer could be used to determine if an object is contained in a given sequence of objects. A sample implementation can be found at this location. My take away from the sample at MSDN is the implementation of the object comparer and more specifically the way the GetHashCode method has been implemented.

References:
1. MSDN Online

Written by cavemansblog

January 10, 2012 at 12:48 am

Linq: OrderByDescending operator

leave a comment »


OrderByDescending is one of the query operators in linq and can be can be to sort data, objects by descending order. Following is an example of an employee collection that is sorted in descending order using the OrderByDescending operator. The following code snippet illustrated the ordering of the Employee objects in descending order:

 class Program
    {
        static void Main(string[] args)
        {
            List<Employee> EmployeeList = new List<Employee>();
            Employee employee = new Employee();
            employee.ID = 1001;
            employee.name = "User 1001";
            EmployeeList.Add(employee);

            employee = new Employee();
            employee.ID = 1007;
            employee.name = "User 1007";
            EmployeeList.Add(employee);

            employee = new Employee();
            employee.ID = 1002;
            employee.name = "User 1002";
            EmployeeList.Add(employee);

            var sortedEmployeed = EmployeeList.OrderByDescending(i => i.ID);
            foreach (var emp in sortedEmployeed)
                Console.WriteLine("EmployeeID: {0}", emp.ID);

        }
    }

    public class Employee
    {
        public int ID { get; set; }
        public string name { get; set; }
    }

Written by cavemansblog

January 8, 2012 at 1:38 am

Linq: Read data from XML file

leave a comment »


In this post I will show you how easy it is to load data into objects from an XML file using Linq. Let us see how we can create two employee objects from the following XML data:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
    <id>1001</id>
    <title>Manager</title>
    <salary>4000</salary>
  </Employee>
  <Employee>
    <id>1002</id>
    <title>Supervisor</title>
    <salary>2000</salary>
  </Employee>
</Employees>

Loading this data is a two step process. Before we start reading our data we have to define a class that will hold the data for each record in the XML file. For this I will create an Employee class with three properties that corresponds to the three elements of the Employee node from the XML data.

    public class Employee
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public int Salary { get; set; }
    }

We are now ready to read the entire XML file using the following code. First we load the XML file into an XDocument object and then create a collection of Employee objects by parsing the XML data using Linq.

XDocument xmlDoc = XDocument.Load("./../../Data.xml");

Employees = (from command in xmlDoc.Descendants("Employee")
select new Employee
{
ID = Convert.ToInt32(command.Element("id").Value),
Title = command.Element("title").Value,
Salary = Convert.ToInt32(command.Element("salary").Value),
}).ToList<Employee>();

foreach (Employee e in Employees)
Console.WriteLine("ID:{0} Title: {1} Salary: {2}", e.ID, e.Title, e.Salary);

//You will need to include the following two namespaces for this code to work
//using System.Xml;
//using System.Xml.Linq;

At this point we should have two Employee objects in the Employee List object and here is the output from executing the above code.

Written by cavemansblog

October 1, 2011 at 1:14 am

OpenXML + Linq = Awesome Office files

leave a comment »


Office Open XML (also informally known as OOXML or OpenXML) is a zipped, XML-based file format developed by Microsoft for representing spreadsheets, charts, presentations and word processing documents. [1] If someone is looking for software to generate MS-Office file programatically, I would highly recommend considering this library. I have recently used OpenXML to generate Excel reports from a windows service. The library was very fast in generating reports with a lot of data and the best part about this library is that it is free 🙂 Microsoft provides a SDK that can be downloaded from here and can very easy used to generate awesome Office reports. Following are some resources for OpenXML development:

Here is a utility function that converts a List of objects into a DataTable, that can be easily exported to an OpenXML file. Basically in the code below, while loop through the contents of the List object, we use reflection to read the List object properties to create the column names of a DataRow object. Data from each List object is then populated in the DataRow object which will then be used to fill our DataTable.

public DataTable ConvertToDataTable(List<EmployeeData> varlist)
{
    DataTable dtReturn = new DataTable();
    // column names
    PropertyInfo[] oProps = null;

    if (varlist == null) return dtReturn;
    foreach (EmployeeData rec in varlist)
    {
        if (oProps == null)
        {
            oProps = ((Type)rec.GetType()).GetProperties();
            foreach (PropertyInfo pi in oProps)
            {
                Type colType = pi.PropertyType;

                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition()
                == typeof(Nullable)))
                {
                    colType = colType.GetGenericArguments()[0];
                }

                dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
            }
        }

        DataRow dr = dtReturn.NewRow();
        foreach (PropertyInfo pi in oProps)
        {
            dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue
            (rec, null);
        }

        dtReturn.Rows.Add(dr);
    }
    return dtReturn;

References:
1. Office Open XML – Wikipedia
2. Open XML SDK 2.0

Written by cavemansblog

September 21, 2011 at 1:37 am

Linq: Stored procedure limitations

leave a comment »


Following are a couple of Linq-to-SQL limitations that are important when considering using stored procedures in the application

  • Stored procedures that use dynamic SQL to return result sets. When a stored procedure contains conditional logic to build a dynamic SQL statement, LINQ to SQL cannot acquire metadata for the resultset because the query used to generate the resultset is unknown until run time.
  • Stored procedures that produce results based on temporary table.

Written by cavemansblog

April 23, 2011 at 11:43 pm

Posted in Dotnet, Linq