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

Linq: How to return a custom type

leave a comment »


In this blog post I am going to show you the C# and VB.Net ways of creating/returning custom typed objects. Let us create an Employee class that will hold our data. Our employee class has three properties Name, Age and Salary. Observe the new feature called “Automatic properties” that only requires the partial code to be written while defining properties. Let us define two constructors, one with arguments and another without arguments (default). The next step is to create a list of these employees. I have defined 6 employee objects via calling both the constructors, followed by adding each of these objects to the Employees typed List object.

    public class employee
    {
        //Automatic properties
        public int Age { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }

        public employee();
        public employee(int age, string name, int salary)
        { this.Age = age; this.Name = name; this.Salary = salary; }
    }

We now have a queriable object that can be used to returned a custom object(s). The query in the example below returns all employees who are older than 22 years and the same time, the employee salary is also recomputed on the fly. The Linq query is made to return the employee Name and Salary as a new object that is different that the Employee class/object that we have defined above.


    class Program
    {
        static void Main(string[] args)
        {
            List<employee> Employees = new List<employee>();
            //old school object instatiation
            employee e = new employee(20, "John", 100);
            Employees.Add(e);
            //object Initializers
            e = new employee { Salary = 200, Name = "Smith", Age = 21 };
            Employees.Add(e);
            e = new employee(22, "Mark", 300);
            Employees.Add(e);
            e = new employee(23, "Dave", 400);
            Employees.Add(e);
            e = new employee(24, "Jeff", 500);
            Employees.Add(e);
            e = new employee(25, "Doug", 600);
            Employees.Add(e);

            var Query = from tmp in Employees
                        where tmp.Age > 22
                        select new
                        {
                            EmployeeFirstName = tmp.Name,
                            EmployeeSalaryPlusCommision = (tmp.Salary + (2 * tmp.Salary))
                        };

            foreach (var q in Query)
                Console.WriteLine("Name: {0}; Salary: {1}", q.EmployeeFirstName, q.EmployeeSalaryPlusCommision);
        }
    }

Following is the VB.Net implementation of the above code.


Public Class employee
    Public Property Age() As Integer
        Get
            Return m_Age
        End Get
        Set(ByVal value As Integer)
            m_Age = Value
        End Set
    End Property
    Private m_Age As Integer
    Public Property Name() As String
        Get
            Return m_Name
        End Get
        Set(ByVal value As String)
            m_Name = Value
        End Set
    End Property
    Private m_Name As String
    Public Property Salary() As Integer
        Get
            Return m_Salary
        End Get
        Set(ByVal value As Integer)
            m_Salary = Value
        End Set
    End Property
    Private m_Salary As Integer
    Public Sub New()
    End Sub
    Public Sub New(ByVal age As Integer, ByVal name As String, ByVal salary As Integer)
        Me.Age = age
        Me.Name = name
        Me.Salary = salary
    End Sub
End Class

Module Module1

    Sub Main()
        Dim Employees As New List(Of employee)()
        'old school object instatiation
        Dim e As New employee(20, "John", 100)
        Employees.Add(e)
        'object Initializers
        e = New employee() With { _
        .Salary = 200, _
        .Name = "Smith", _
        .Age = 21 _
        }
        Employees.Add(e)
        e = New employee(22, "Mark", 300)
        Employees.Add(e)
        e = New employee(23, "Dave", 400)
        Employees.Add(e)
        e = New employee(24, "Jeff", 500)
        Employees.Add(e)
        e = New employee(25, "Doug", 600)
        Employees.Add(e)

        Dim Query = From tmp In Employees Where tmp.Age > 22
        Select New With { _
        .EmployeeFirstName = tmp.Name, _
        .EmployeeSalaryPlusCommision = (tmp.Salary + (2 * tmp.Salary)) _
        }

        For Each q As Object In Query
            Console.WriteLine("Name: {0}; Salary: {1}", q.EmployeeFirstName, q.EmployeeSalaryPlusCommision)
        Next

    End Sub

End Module

PS: Check this Developer Fusion, a website that helped me convert my C# code to Vb.Net

[/sourcecode] 

Written by coolgirlsblog

March 28, 2011 at 9:35 am

Posted in Dotnet, Linq

Tagged with , ,