.Net Linq GroupBy anagram comparer example

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

namespace CsharpGroupByComparer
{
    class GroupByComparer
    {
        static void Main(string[] args)
        {
            var anagrams = new List<string> { "disks", "skids", "freed", "defer", "begin", "being", "note", "xxxx", };

            var results = anagrams.GroupBy(x => x.ToLower(), new AnagramComparer()).Where(x => x.Count() > 1).ToList();

            results.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(IGrouping<string, string> results)
        {
            foreach (var result in results)
                Console.WriteLine(result);
        }

        private class AnagramComparer : IEqualityComparer<string>
        {
            public bool Equals(string a, string b)
            {
                return GetString(a) == GetString(b);
            }

            public int GetHashCode(string obj)
            {
                return GetString(obj).GetHashCode();
            }

            private static string GetString(string word)
            {
                return new string(word.ToCharArray().OrderBy(x => x).ToArray());
            }
        }
    }
}

.Net Convert string to List<> of Integer

using System;
using System.Linq;

namespace CsharpListStringtoListInt
{
    class ConvertListToIntDemo
    {
        static void Main(string[] args)
        {
            const string listOfStrings = "1,2,3,4,5";

            var listOfInts = listOfStrings.Split(',').Select(int.Parse).ToList();

            Console.WriteLine(listOfInts.GetType());
            
            Console.ReadKey();
        }
    }
}

.Net Skip<> and Take<> example

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

namespace CsharpSkipTakeExample
{
    static class SkipTakeDemo
    {
        static void Main(string[] args)
        {
            var months = new List<string>
                           {
                               "January",
                               "February",
                               "March",
                               "April",
                               "May",
                               "June",
                               "July",
                               "August",
                               "September",
                               "October",
                               "November",
                               "December"
                           };

            // Get the first 6 months
            var firstSixMonths = months.GetRange(0, 6);

            firstSixMonths.ForEach(Print);

            Console.WriteLine();

            // Take the first 3 months
            var firstThreeMonths = months.Take(3).ToList();

            firstThreeMonths.ForEach(Print);

            Console.WriteLine();

            // Months ending with y
            var monthsEndingWithY = months.TakeWhile(x => x.EndsWith("y")).ToList();

            monthsEndingWithY.ForEach(Print);

            Console.WriteLine();

            // Skip the first Month by condition
            var skipTheFirstMonth = months.SkipWhile(x => x.StartsWith("J")).ToList();

            skipTheFirstMonth.ForEach(Print);

            Console.ReadKey();
        }

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

.Net List<>.TrueForAll example

using System;
using System.Collections.Generic;

namespace CsharpTrueForAll
{
    public static class TrueForAllDemo
    {
        public static void Main()
        {
            var countries = new List<string> {"England", "Scotland", "Ireland", "Wales"};

            Console.WriteLine(countries.TrueForAll(CheckEnding));

            Console.ReadKey();
        }

        private static bool CheckEnding(string input)
        {
            return input.ToLower().EndsWith("land");
        }
    }
}

A simple ASP.Net MVC HTML Helper to truncate a string at an arbitrary length

public static MvcHtmlString DisplayNewsSearchSummary(this HtmlHelper htmlHelper, string input, int requiredLength, string ending = "...")
{
    // Validate and sanity check first...

   var requiredtext = input.Substring(0, requiredLength - 1);

   var ouputtext = string.Concat(requiredtext.Substring(0, requiredtext.LastIndexOf(' ')), ending);

   return new MvcHtmlString(descriptionText);
}

.Net C# closures

A quick demo of a C# closure, thanks to Justin Etheredge at

http://www.codethinked.com/c-closures-explained

A closure can be defined as:

A first-class function with free variables that are bound in the lexical environment.

Here’s a good post on Stack Overflow regarding closures What are closures in .Net and another post discussing Multithreading and closures.

The example below is a simple implementation of a closure.

using System;

namespace CsharpClosure
{
    class Program
    {
        static void Main()
        {
            var hWOutput = HwFunc();
            
            Console.WriteLine(hWOutput("Hello"));
       
            Console.WriteLine(hWOutput("Hello"));

            Console.WriteLine(hWOutput("Hello"));

            Console.ReadKey();
        }

        private static Func<string, string> HwFunc()
        {
            var myVar = "";
            Func<string, string> result = input =>
                                           {
                                               myVar = myVar + " World";
                                               return input + myVar;
                                           };
            return result;
        }
    }
}

.Net Linq ConvertAll<> Example

using System;
using System.Collections.Generic;

namespace CsharpLinqConvertAllExample
{
    class Program
    {
        static void Main(string[] args)
        {

            var intList = new List<int>
                              {
                                  1,
                                  2,
                                  3,
                                  4,
                                  5
                              };

            var stringList = intList.ConvertAll(x => x.ToString());

            stringList.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(object obj)
        {
            Console.WriteLine(obj);
        }
    }
}

.Net using the IS operator

using System;

namespace CsharpISOperator
{
    internal class TestClassOne { }
    internal class TestClassTwo { }
    internal class TestClassThree : TestClassOne { }

    public class Program
    {
        static void TestIsOperator(object inputObject)
        {
            TestClassOne testClassOne;
            TestClassTwo testClassTwo;

            if (!(inputObject is TestClassOne))
            {
                if (inputObject is TestClassTwo)
                {
                    Console.WriteLine("inputObject is Class2");
                    testClassTwo = (TestClassTwo)inputObject;
                }
                else
                {
                    Console.WriteLine("inputObject is neither Class1 nor Class2.");
                }
            }
            else
            {
                Console.WriteLine("inputObject is Class1");
                testClassOne = (TestClassOne)inputObject;
            }

            Console.ReadKey();
        }

        static void Main()
        {
            var classOne = new TestClassOne();
            var testClassTwo = new TestClassTwo();
            var testClassThree = new TestClassThree();

            TestIsOperator(classOne);
            TestIsOperator(testClassTwo);
            TestIsOperator(testClassThree);
        }
    }
}

.Net using the Yield keyword

using System;
using System.Collections;

namespace YieldDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var i in Power(2, 28))
            {
                Console.WriteLine("{0} ", i);
            }
            
            Console.ReadKey();
        }
        
        private static IEnumerable Power(int number, int exponent)
        {
            var counter = 0;
            var result = 1;
            
            while (counter++ < exponent)
            {   
                yield return result = result * number;
            }
        }
    }
}