.NET Tip: Basic Data Manipulation with LINQ

LINQ provides a flexible means to work with your data that wasn't available before. You now have access to SQL-like capabilites that you can apply to your own data types or to built-in data types. In this tip, you will learn how to sort your data and how to reshape the data that your LINQ query returns. To begin, set up some data for the examples that follow with a Person class and an array of Person objects:

public class Person
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
   public string Occupation { get; set; }
}

Person[] People = new Person[] {
   new Person { FirstName = "Jay", LastName = "Miller",
                Age = 41, Occupation = "Software Engineer" },
   new Person { FirstName = "Bill", LastName = "Gates",
               Age = 52, Occupation = "Billionaire" },
   new Person { FirstName = "George", LastName = "Bush",
                Age = 62, Occupation = "President" }
};

This code defines a Person class with four properties to hold a first name, last name, age, and occupation. The People variable then is defined as an array of Person objects and initialized with three entries. Start by taking a look at how to sort the data. LINQ provides an orderby clause that you use with the from statement. The first example selects all of the items in People, sorts them by LastName then FirstName, and then outputs them to the Debug window. The code looks like this:

// Sort the list of people by LastName, FirstName
var PeopleByName = from p in People
                   orderby p.LastName ascending,
                   p.FirstName ascending
                   select p;

foreach (var p in PeopleByName)
   Debug.Print(p.LastName + ", " + p.FirstName);

Here is the output from the above example:

Bush, George
Gates, Bill
Miller, Jay

As you would expect, the data was sorted in order by LastName. As you can see, orderby supports sorting on multiple keys and the ability to sort any given key in either ascending or descending order.

The other ability of LINQ I'd like to show you is reshaping the result or your query. In the first example, the select p clause simply returned each data element in its entirety. The select clause also enables you to return a data type that is different from the base data you are querying. In this example, I will return a new data type from the query that includes the Age property from the original data, as well as a Name that is a concatenation of the FirstName and LastName properties.

// Sort the list of people by Age and combine FirstName
// and LastName into a single Name field
var PeopleByAge = from p in People
                  orderby p.Age descending
                  select new { p.Age, Name = p.FirstName + " " +
                               p.LastName };

foreach (var p in PeopleByAge)
    Debug.Print(p.Age + " " + p.Name);

Visual Studio can infer the data type that is returned from the query, so in the foreach loop that outputs each element, IntelliSense is available. This makes it extremely easy to reshape the data depending upon how you need to manipulate it and have full support in the IDE. I also changed the orderby clause to sort the data in descending order by Age so you can see an example of a different sort. The output looks like this:

62 George Bush
52 Bill Gates
41 Jay Miller

There is so much more that LINQ can do for you application. I was a little slow to realize just how big an impact LINQ could have on my applications. I hope that you explore LINQ's other abilities and find ways to simplify your applications.

About the Author

Jay Miller is a Software Engineer with Electronic Tracking Systems, a company dedicated to robbery prevention, apprehension, and recovery based in Carrollton, Texas. Jay has been working with .NET since the release of the first beta and is co-author of Learn Microsoft Visual Basic.Net In a Weekend. Jay can be reached via email at jmiller@sm-ets.com.



Comments

  • blueskycyber.com

    Posted by blueskycyber on 02/19/2009 03:17am

    Hi guy! You can find and download resources on your demand from the following address:
    
    ----->>> blueskycyber.com <<<-----
    
    What we have: hotnews, design, Graphics, ebooks, download resources, cracks, serials, keygens, softwares, wallpapers and much more...

    Reply
  • blueskycyber.com

    Posted by blueskycyber on 02/19/2009 03:16am

    Hi guy! You can find and download resources on your demand from the following address: ----->>> blueskycyber.com <<<----- What we have: hotnews, design, Graphics, ebooks, download resources, cracks, serials, keygens, softwares, wallpapers and much more...

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • CentreCorp is a fully integrated and diversified property management and real estate service company, specializing in the "shopping center" segment, and is one of the premier retail service providers in North America. Company executives travel a great deal, carrying a number of traveling laptops with critical current business data, and no easy way to back up to the network outside the office. Read this case study to learn how CentreCorp implemented a suite of business continuity services that included …

Most Popular Programming Stories

More for Developers

RSS Feeds