Created
November 13, 2012 20:18
-
-
Save sophie-eihpos/4068128 to your computer and use it in GitHub Desktop.
Extension Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Text; | |
using System; | |
namespace CustomExtensions | |
{ | |
//Extension methods must be defined in a static class | |
public static class StringExtension | |
{ | |
// This is the extension method. | |
// The first parameter takes the "this" modifier | |
// and specifies the type for which the method is defined. | |
public static int WordCount(this String str) | |
{ | |
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length; | |
} | |
} | |
} | |
namespace Extension_Methods_Simple | |
{ | |
//Import the extension method namespace. | |
using CustomExtensions; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string s = "The quick brown fox jumped over the lazy dog."; | |
// Call the method as if it were an | |
// instance method on the type. Note that the first | |
// parameter is not specified by the calling code. | |
int i = s.WordCount(); | |
System.Console.WriteLine("Word count of s is {0}", i); | |
} | |
} | |
} | |
/********************************* Distinct 1 **************************************/ | |
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> collection, Func<T, T, Boolean> comparer) | |
{ | |
return collection.Distinct(new LinqExtensions.Comparer<T>(comparer)); | |
} | |
/********************************* Distinct 2 **************************************/ | |
public static class EnumerableExtensions | |
{ | |
public static IEnumerable<TKey> Distinct<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector) | |
{ | |
return source.GroupBy(selector).Select(x => x.Key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment