Wednesday, June 16, 2010

C#:: Code Factory



















































Split string in equal sized chunks
private IEnumerable<string> SplitIntoChunks(string text, int chunkSize)
{
int offset = 0;
while (offset < text.Length)
{
int size = Math.Min(chunkSize, text.Length - offset);
yield return text.Substring(offset, size);
offset += size;
}
}


source: http://stackoverflow.com/questions/1632078/split-string-in-512-char-chunks-c


 
Find the Date for the Start of the Week?

public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = dt.DayOfWeek - startOfWeek;
if (diff < 0)
{
diff += 7;
}

return dt.AddDays(-1 * diff).Date;
}
}


source: http://stackoverflow.com/questions/38039/how-can-i-get-the-datetime-for-the-start-of-the-week


 
Chained null checks and the Maybe monad - CodeProject

OLD


string postCode = null;
if (person != null && person.Address != null && person.Address.PostCode != null)
{
postCode = person.Address.PostCode.ToString();
}


NEW



public static TResult With<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator)

    where TResult : class


    where TInput : class


{


    if (o == null) return null;


    return evaluator(o);


}



string postCode = this.With(x => person)

                      .With(x => x.Address)


                      .With(x => x.PostCode);


source: http://www.codeproject.com/KB/cs/maybemonads.aspx
 
C# Puzzlers

http://streaming.ndc2010.no/tcs/?id=E915B78B-D9B7-4CE9-96DA-2B794391AD2F


 

No comments: