Most Used Enumerable(T) Methods

Here’s the Enumerable methods I use the most.  All of these are available in the .NET 4.0 Framework.

Enumerable.Any() – Determines whether a sequence contains any elements.

Enumerable.Empty<T>() – Returns an empty IEnumerable<T> that has the specified type argument.

Enumerable.Distinct() – Returns distinct elements from a sequence by using the default equality comparer to compare values.

Enumerable.FirstOrDefault() – Returns the first element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Count() – Returns the number of elements in a sequence.

Enumerabel.LastOrDefault() – Returns the last element of a sequence, or a default value if the sequence contains no elements.

Enumerable.Max() – Returns the maximum value in a generic sequence.

Enumerable.Min() – Returns the minimum value in a generic sequence.

Enumerable.Select() – Projects each element of a sequence into a new form.

Enumerable.ToArray() – Creates an array from a IEnumerable<T>.

Enumerable.Where() – Filters a sequence of values based on a predicate.

Here’s a link to the MSDN site that lists all the available methods

Tuple

Tuple is a new class in the .Net 4.0 framework which allows you to hold up to 8 components in a single class.  The alternative is creating a specific class with properties for each component.  This makes this class ideal for the following situations:

1.  Returning multiple values from a method without the use of out parameters

2.  Pass multiple values to a method using a single class.

3.  Collections of Tuples can be used to represent database information or array data.

4.  Easy access and manipulation of a data set.

Here’s an example using Tuple<T1, T2>

class Program
    {
        static void Main(string[] args)
        {
            int dividend, divisor;
            Tuple<int, int> result;

            dividend = 136945; divisor = 178;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            dividend = Int32.MaxValue; divisor = -2073;
            result = IntegerDivide(dividend, divisor);
            if (result != null)
                Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}",
                                  dividend, divisor, result.Item1, result.Item2);
            else
                Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor);

            Console.ReadLine();

        }

        private static Tuple<int, int> IntegerDivide(int dividend, int divisor)
        {
            try
            {
                int remainder;
                int quotient = Math.DivRem(dividend, divisor, out remainder);
                return new Tuple<int, int>(quotient, remainder);
            }
            catch (DivideByZeroException)
            {
                return null;
            }
        }

    }

A Few Good Resources

These are some recent books I’ve read related to software.

Clean Code:  A Handbook of Agile Software Craftsmanship

I highly recommend this book.  Go to the Amazon link above to read more about.

The Design of Design – Essays from a Computer Scientist

An interesting book that discusses the various design approaches.

The Art of Unit Testing

The definitive book on how to properly unit test.

Head First Design Patterns

A straightforward reference to many design patterns with easy to understand examples and excellent descriptions.

Design Patterns:  Elements of Reusable Object-Oriented Software

Another excellent reference for many design patterns used in software today.

ThreadPool

I discovered this class the other day.  It’s actually been around for a while as part of the .NET 2.0 framework.  You can use it to run a method in a different thread.  Here’s a description from the MSDN site.

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. (See Using Threading for background information.) This leaves the primary thread free to perform other tasks asynchronously.

Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.

Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.

Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are placed in queue until they can be serviced as threads become available.

Here’s a very simple example that illustrates how the main execution thread continues without waiting for the “DoSomething” thread to complete.  ≈

    class ThreadPoolExample
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start");
            ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), args);

            Console.WriteLine("Finish");

            Console.ReadLine();
        }

        private static void DoSomething(object args)
        {
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(100);
                Console.WriteLine(i);
            }
        }
    }

Here’s the output:

 

 

 

 

 

 

If we needed to know when the work was finished from Threadpool, then a ManualResetEvent could be passed into a WaitHandle like the example described here.

A Few .NET String Functions (Split, Join, IsNullOrEmpty, IsNullOrWhiteSpace)

Here’s some of my favorite String functions in .NET.

    class StringFunctions
    {
        static void Main(string[] args)
        {
            // Check for Null or Empty
            const string emptyString = "";
            if (String.IsNullOrEmpty(emptyString))
                Console.WriteLine("String is Empty or Null");

            // Join an array of integers together
            Collection array = new Collection() { 1, 2, 3 };
            Console.WriteLine(String.Join(",", array));

            // Split a string into an array
            ICollection fullStringArray = "The cat in the hat".Split(' ');
            foreach (var element in fullStringArray)
                Console.WriteLine(element);

            // Split ignoring emtpy spaces
            const string numberList = "1,2,3,4,,6";
            ICollection trimmedStringArray = numberList.Split(new[] { ',' }, numberList.Length, StringSplitOptions.RemoveEmptyEntries);
            foreach (var element in trimmedStringArray)
                Console.WriteLine(element);

            Console.ReadLine();
        }
    }

Output:

 

 

 

 

 

 

Here’s a link to an article with more examples for Split.

IsNullOrWhiteSpace is new in .NET 4.0. It’s similar to IsNullOrEmpty, but it also will catch strings that contain only empty spaces. In prior versions, you would have to trim the string prior to calling IsNullOrEmpty if you wanted to treat strings with only empty spaces as empty strings.

Action(T)

I recently discovered the Action in .NET.  It’s in version 4.0 of the .NET framework.  They’re very similar to delegates, but they require less setup.

Type Parameters

in T
The type of the parameter of the method that this delegate encapsulates. 

This type parameter is contravariant. That is, you can use either the type you specified or any type that is less derived. For more information about covariance and contravariance, see Covariance and Contravariance in Generics.

Parameters

obj
Type: T
The parameter of the method that this delegate encapsulates.

Click here for the complete definition with more examples from the MSDN Library.

Here’s an example:

    class ActionExample1
    {
        static void Main(string[] args)
        {
            List<String> names = new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            ShowOutput(names, Print);
        }

        private static void ShowOutput(List<String> argument, Action<string> action)
        {
            foreach (var arg in argument)
            {
                action(arg);
            };
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Output:

You can also assign a lambda expression to an Action<T> delegate instance, as the following example illustrates.

    class ActionExampleLamda
    {
        static void Main3(string[] args)
        {
            Action<string> messageTarget;

            // Display the contents of the list using the Print method.
            messageTarget = s => Print(s);

            messageTarget("Hello World");
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }

Here’s another example that utilizes the ForEach directly on the collection which takes an Action as an argument.

    class ActionExample2
    {
        static void Main2(string[] args)
        {
            List names = new List();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");

            // Display the contents of the list using the Print method.
            names.ForEach(Print);
        }

        private static void Print(string s)
        {
            Console.WriteLine(s);
        }
    }