ISourceCode

Make the frequent cases fast and the rare case correct

Category Archives: Algorithms

C# – Writing an Extension Method

A simple extension method that extends the List class. The extension method accepts a Func delegate. The algorithm is to multiply each element in the list by 2. The Func delegate points to this algorithm method.

using System;
using System.Collections.Generic;

namespace ExtensionMethodFunc
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();

            for (int i = 1; i <= 10; i++)
                list.Add(i);

            // Approach 1 to call the extension method with the Func delegate
            foreach (int i in list.GetMyList(MultiplyByTwo))
                Console.WriteLine(i);

            // Approach 2, Func delegate explicitly declared pointing to the method
            //Func<int, int> algo = MultiplyByTwo;
            //foreach (int i in list.GetMyList(algo))
            //	Console.WriteLine(i);

            // Approach 3, using an anonymous method, C# 2.0 feature
            //Func<int, int> algo = delegate(int x) { return x * 2; };
            //foreach (int i in list.GetMyList(algo))
            //  Console.WriteLine(i);

            // Approach 4, using lambda expression which is an anonymous function
            // C# 3.0 feature
            //Func<int, int> algo = x => x * 2;
            //foreach (int i in list.GetMyList(algo))
            //	Console.WriteLine(i);

            // Approach 5, using lambda expression without explicitly declaring a func
            //foreach (int i in list.GetMyList(m => m * 2))
            //	Console.WriteLine(i);

            // Approach 6, redundant lambda calling original method, not to be used
            //Func<int, int> algo = x => MultiplyByTwo(x);
            //foreach (int i in list.GetMyList(algo))
            //    Console.WriteLine(i);

            Console.ReadKey();
        }

        private static int MultiplyByTwo(int value)
        {
            return value * 2;
        }
    }

    static class ExtensionMethods
    {
        // Non generic implementation of extension method
        //
        //public static IEnumerable<int> GetMyList(this IEnumerable<int> list, Func<int, int> selector)
        //{
        //	foreach (int item in list)
        //		yield return selector(item);
        //}

        public static IEnumerable<TResult> GetMyList<TSource, TResult>(this IEnumerable<TSource> list, 
            Func<TSource, TResult> selector)
        {
            foreach (TSource item in list)
                yield return selector(item);
        }
    }
}

C# – Tree Traversal using Parallel.Invoke Method.

Used the Parallel.Invoke method from Task Parallel library.

Invoke(Action[]) executes the tasks possibly in parallel.

Pass a list of actions to the method.

I already had a tree and i plugged this method.For more check this article

Read more of this post

C# – LINQ – Check if two strings are Anagrams using Dictionary data structure

Below is code written in C# and LINQ to check if two strings are anagram of each other using the .NET Dictionary class which is a hash table.

Ordering the dictionary according to the key in order to do a SequenceEqual might not be elegant since a dictionary is meant to be unordered ( take a look at the dump).

Execute it using Linqpad.

static void Main()
{
    string str1 = "ab# wrr2b";
    string str2 = "b#rba2 rw";

    Dictionary<char, int> dict1, dict2 = new Dictionary<char, int>();

    dict1 = StringDictionary(str1);
    dict2 = StringDictionary(str2);

    if (dict1.OrderBy(d => d.Key).SequenceEqual(dict2.OrderBy(d => d.Key)))
    {
        Console.WriteLine("True");
    }
    else Console.WriteLine("False");
}

public static Dictionary<char, int> StringDictionary(string str)
{
    return str.GroupBy(s => s).ToDictionary(d => d.Key, d => d.Count()).Dump();
}

OUTPUT:

anagramcheck

Alternatively SortedDictionary class can also be used

static void Main(string[] args)
{
	string str1 = "ab# wrr2b";
	string str2 = "b#rba2 r";

	SortedDictionary<char, int> dict1, dict2 = new SortedDictionary<char, int>();

	dict1 = StringDictionary(str1);

	dict2 = StringDictionary(str2);

	if (dict1.SequenceEqual(dict2))
	{
		Console.WriteLine("True");
	}
	else Console.WriteLine("False");

	Console.ReadKey();
}

public static SortedDictionary<char, int> StringDictionary(string str)
{
	return new SortedDictionary<char, int>(str.GroupBy(s => s).ToDictionary(d => d.Key, d => d.Count()));
}

Couple of years ago i wrote an article about the same algorithm and coded in C++ and Java.

Group a type with DateTime member based on the split of a year as quarterly/half yearly using C# and LINQ

In this post there is code to classify a type employee with members name and joindate into a particular quarter of a year based on their joining date.

You can run the code on linqpad or VS.

If you want to classify it on half yearly basis change GroupBy(o => (o.joindate.Month – 1) / 3) to
GroupBy(o => (o.joindate.Month – 1) / 6)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DateFilter
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> emp = new List<Employee>()
			{ 
				new Employee 
				{ 
					name = "Steve", joindate = DateTime.Parse("3/28/2012", System.Globalization.CultureInfo.InvariantCulture)
				},
				new Employee 
				{ 
					name = "John", joindate = DateTime.Parse("5/28/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Chin", joindate = DateTime.Parse("12/21/2012", System.Globalization.CultureInfo.InvariantCulture) 
				},
				new Employee 
				{ 
					name = "Henry", joindate = DateTime.Parse("12/25/2012", System.Globalization.CultureInfo.InvariantCulture) 
				}
			};

            // uncomment lines below to view the dump on linqpad (pasted below)
            /*emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList()).Dump();*/

            var query = emp.
            Select(o => new Employee { name = o.name, joindate = o.joindate })
            .GroupBy(o => (o.joindate.Month - 1) / 3)
            .ToDictionary(kvp => kvp.Key, kvp => kvp.ToList());

            foreach (KeyValuePair<int, List<Employee>> kvp in query)
            {
                Console.WriteLine(kvp.Key.ToString());

                foreach (Employee employee in kvp.Value)
                {
                    Console.WriteLine(employee.name);
                }
            }

            Console.ReadKey();
        }
    }

    class Employee
    {
        public string name { get; set; }
        public DateTime joindate { get; set; }
    }
}

This is a snapshot from linqpad. The key value 0,1,2 and 3 are the quarters. This helped me get a report of employees hired on a quarterly basis.

datefilter

Software Products and their programming languages

General stuff on programming languages used for various
Software Products

Follow

Get every new post delivered to your Inbox.

Join 27 other followers