Anonymous Types In LINQ

One really cool thing with C# .NET LINQ is the ability to take a query and output the data to an anonymous types. This work with either type of query be it comprehension or method syntax. The one drawback is that you can’t access this directly because it inherits directly from object. You would need to cast it as new defined type (class) to do this. You will see me doing this different ways thru the upcoming examples. How you choose to do it is based on your own personal preferences.

AnonTypesSolution AnonTypesProgram

 

Program.cs Code Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Xml.Linq;
using System.Diagnostics;

namespace MyLinq
{
    class Program
    {
        /// <summary>
        /// Demonstrating a simple way to define and use anonymous types.
        /// </summary>
        /// <param name="args"></param>

        static void Main(string[] args)
        {
            showAnonymousTypes();

            Console.ReadLine();
        }

        //Private Methods
        //
        private static void showAnonymousTypes()
        {
            // Demonstrating how you can use an anonymous type to get the processes running
            // on the computer this program is on.
            var processList =
                from processes in Process.GetProcesses()
                orderby processes.Threads.Count descending,
                processes.ProcessName ascending
                select new                                          // This is where the anonymous type creation is happening.
                {
                    processes.ProcessName,
                    ThreadCount = processes.Threads.Count
                };

            // Now let's display the processes collected from the anonymous type.
            Console.WriteLine("****Displaying The Process List*****");
            foreach (var process in processList)
            {
                Console.WriteLine("{0,25} {1,4:D}", process.ProcessName, process.ThreadCount);
            }
        }
    }
}

This is a really simple example of taking all the processes running on a computer, ordering them by the thread count, and using an anonymous type to define the object properties. Again this is a really simple example. However it should give you a glimpse into the powerful nature of using these kinds of types in LINQ queries.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s