Common LINQ operations in C#

Created by
Thursday, June 23, 2016

LINQ (Language Integrated Query) is an integrated query language that provides developers with a way to query in their familiar environment. In a nutshell we can write queries in our code. In this example we will be working with C#.

In this short introduction we will be writing everything into a small Console Application that you can download for your own use.

Lets begin by setting up two classes called [User] and [Country]

    public class User
    {
        public User(string firstName, string lastName, int age, string sex, string city)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
            Sex = sex;
            City = city;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Sex { get; set; }
        public string City { get; set; }
    }

 

    public class Country
    {
        public Country(string name, string city)
        {
            Name = name;
            City = city;
        }

        public string Name { get; set; }

        public string City { get; set; }
    }

Once we have these we are going to set up some static data as follows. You should modify the above classes and add in some of your own properties to get more familiar.

        public static List<User> GetUsers()
        {
            // Create a list 
            List<User> users = new List<User>();

            // Add some users to our list
            users.Add(new User("John", "Doe", 20, "M", "San Francisco"));
            users.Add(new User("Jane", "Doe", 30, "F", "Vancouver"));
            users.Add(new User("Mark", "Penn", 18, "M", "Dublin"));
            users.Add(new User("Peter", "Jones", 40, "M", "Galway"));
            users.Add(new User("Lilly", "Doe", 26, "F", "Paris"));
            users.Add(new User("David", "Carrol", 20, "M", "Vancouver"));
            users.Add(new User("Francis", "Kelly", 20, "F", "Calgary"));
            users.Add(new User("James", "Paul", 26, "M", "New York"));
            users.Add(new User("David", "Carrol", 20, "M", "Vancouver"));

            return users;
        }

        public static List<Country> GetCountries()
        {
            List<Country> countries = new List<Country>();

            countries.Add(new Country("San Francisco", "America"));
            countries.Add(new Country("Vancouver", "Canada"));
            countries.Add(new Country("Dublin", "Ireland"));
            countries.Add(new Country("Galway", "Ireland"));
            countries.Add(new Country("Paris", "France"));
            countries.Add(new Country("Vancouver", "Canada"));
            countries.Add(new Country("Calgary", "Canada"));
            countries.Add(new Country("New York", "America"));
            countries.Add(new Country("Vancouver", "Canada"));

            return countries;
        }

Let's set up our static Main method of our console application to build two lists containing all of this data. Once we have this we can go ahead and look through our users writing them to the console.

Filtering:

Similar to the where clause in SQL this allows us to apply simple conditions to our collections. Here we are filtering our collection for all users that are male, or “M”.

        public static void LINQ_Filtering(List<User> users)
        {
            
            // Query the collection of users for males and return the users first name
            var queryMales = from user in users
                where user.Sex == "M"
                select user.FirstName;

            foreach (var male in queryMales)
            {
                Console.WriteLine(male);
            }

            Console.WriteLine("\n");

            // Query the collection of users for males and return the full user
            var queryMalesFull = from user in users
                where user.Sex == "M"
                select user;

            foreach (var male in queryMalesFull)
            {
                Console.WriteLine(male.FirstName + ", " + male.LastName + ", " + male.City);
            }

            Console.WriteLine("\n");
        }

 

Ordering:

We may also want to order our data asc/desc. Usually this arises when we wish to arrange our items by a certain date or a given id. Here we are simply going to grab all the users that are aged 20 and order them by their first name descending.

        public static void LINQ_Ordering(List<User> users)
        {
            // Query all the 20 year olds and order them by first name descending
            var queryAge = from user in users
                           where user.Age == 20
                           orderby user.FirstName descending
                           select user;

            foreach (var user in queryAge)
            {
                Console.WriteLine(user.FirstName);
            }
            Console.WriteLine("\n");
        }

 

Grouping:

Grouping is a common request. Here we are grouping our users by their city. Try adding in more data and grouping larger sets.

        public static void LINQ_Grouping(List<User> users)
        {
            // Query all users and group by residence
            var queryResidence = from user in users
                                 group user by user.City;

            foreach (var user in queryResidence)
            {
                Console.WriteLine(user.Key);
            }
            Console.WriteLine("\n");
        }

 

Joining:

A join arises when we wish to combine two collections of data based on some common property. In the User class i have given them all a city where they reside. In the Country class i have matched a city to a country. We then wish to list out the users via their first name and the country they live in.

        public static void LINQ_Joining(List<User> users, List<Country> countries)
        {
            // Query and join users and countries by city
            var queryInnerJoin = from u in users
                                 join c in countries on u.City equals c.City
                                 select new { u.FirstName, c.Name };

            foreach (var location in queryInnerJoin)
            {
                Console.WriteLine("{0} is from {1}", location.FirstName, location.Name);
            }
        }


As you can imagine you can further extend these basic operations in many ways.

Tags:
linq
c#
0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
1 comment
Monday, July 11, 2016

Simple and to the point!! I like it..