Skip to main content

Posts

Showing posts from 2016

Extension Method for returning default values

Extension Method for returning default values static class ExtensionsThatWillAppearOnEverything { public static T IfDefaultGiveMe < T >( this T value , T alternate ) { if ( value . Equals ( default ( T ))) return alternate ; return value ; } } var result = query . FirstOrDefault (). IfDefaultGiveMe ( otherDefaultValue ); Or we can use the one shown below ,though its not an extension method. var result = query . FirstOrDefault () ?? otherDefaultValue ;

Extension Methods in C#

Extension Methods in C# using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExtensionMethodsSample {     using MyExtensionMethod;     class Program     {          static void Main(string[] args)         {             string firstName = "Anish";             var res = firstName.MySampleExtensionMethod();             Console.ReadLine();         }     } } namespace MyExtensionMethod {     public static class MyExtensionMethod {          public static string MySampleExtensionMethod(this string inputString)         {             return inputString.ToUpperInvariant();         }     } ...

Grouping and joining in LINQ

Grouping and joining in LINQ foreach ( var line in data . GroupBy ( info => info . metric ) . Select ( group => new { Metric = group . Key , Count = group . Count () }) . OrderBy ( x => x . Metric ) dept needOn status foo 5 / 1 / 2011 closed foo 5 / 1 / 2011 closed foo 5 / 1 / 2011 open foo 5 / 1 / 2011 open Output Required dept needOn status count foo 5 / 1 / 2011 closed 4 foo 5 / 1 / 2011 open 2 Solution: var query3 = from q3 in query2 group q3 by new { q3 . Dept , q3 . NeedOnWeek , q3 . Status } into g select new { dept = g . Key . Dept , needOnWeek = g . Key . NeedOnWeek , status = g . Key . Status , count = g . Count () ...