Signum Framework Logo
"Open framework that encourages convention over configuration, using C# code,
not XML files, to model at the right level of abstraction and achieve deadlines.
...but also has a full Linq provider, and syncs the schema for you!"
Login
RSS

Search

»



Main
Index
Map
Videos
Download
Source code
Tutorials
Forum
FAQ



Image



PoweredBy


ArrayExtensions

Extensions that take or generate arrays

Initialize

Initializes every cell of the array with a provided function.

public static T[,] Initialize<T>(this T[,] array, Func<int,int,T> valueXY)
public static T[, ,] Initialize<T>(this T[, ,] array, Func<int, int, int, T> valueXYZ)

Example:

new int[2, 2].Initialize((i, j) => i + j);
//returns: new[,] { { 0, 1 }, { 1, 2 } }; 

ToArray

Another overload of ToArray method that takes a xPos function, shuffling the values as they are introduced:

public static S[] ToArray<T,S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos)
public static S[,] ToArray<T, S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos, Func<T, int> yPos)
public static S[, ,] ToArray<T, S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos, Func<T, int> yPos, Func<T, int> zPos)

Example:

Point[] points = new[]{new Point(0,0), new Point(1,1)};
bool[,] board = points.ToArray(p=>true, p=>p.X, p.Y); 
//returns: new[,] { { true, false }, { false, true } }; 

Now there's also some overload that takes the length of the resulting array as a parameter. It's more efficient because avoids enumerating the collection twice.

public static S[] ToArray<T, S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos, int xLength)
public static S[,] ToArray<T, S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos, Func<T, int> yPos, int xLength, int yLength)
public static S[, ,] ToArray<T, S>(this IEnumerable<T> collection, Func<T, S> value, Func<T, int> xPos, Func<T, int> yPos, Func<T, int> zPos, int xLength, int yLength, int zLength)

Row and Column

Given a bi-dimensional array and a row (or column) index, returns all the elements in this row.

A row is the sequence of elements _,row A column is the sequence of elements column,_

public static IEnumerable<T> Row<T>(this T[,] data, int row)
public static IEnumerable<T> Column<T>(this T[,] data, int column)

Result:

int[,] arrays = new[,] { { 0, 1, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };

arrays.Column(1).ToString(""); //Returns: 456

arrays.Row(1).ToString(""); //Returns: 158

AddRow and AddColumn

Create a new bi-dimensional array inserting a row (or a column) at a given position:

public static T[,] AddRow<T>(this T[,] values, int pos, T[] newValues)
public static T[,] AddRow<T>(this T[,] values, int pos, Func<int, T> newValue)

public static T[,] AddColumn<T>(this T[,] values, int pos, T[] newValues) public static T[,] AddColumn<T>(this T[,] values, int pos, Func<int, T> newValue)

Example:

 var a = new[,] { { 1, 2 }, { 3, 4 } }.AddColumn(2, new[] { 5, 6 });

Note that when using array initialization you are defining Columns, not Rows

SelectArray

Maps each element from a given bi and three dimensional array to a new one. There are overloads that give the coordinates to the selector as well.

public static S[,] SelectArray<T,S>(this T[,] values, Func<T,S> selector)
public static S[,] SelectArray<T, S>(this T[,] values, Func<int, int, T, S> selector)

public static S[, ,] SelectArray<T, S>(this T[, ,] values, Func<T, S> selector) public static S[, ,] SelectArray<T, S>(this T[, ,] values, Func<int, int, int, T, S> selector)

Example:

var a = new[,] { { 1, 2 }, { 3, 4 } }.SelectArray(n => 4 - n);
//Returns: new[,] { { 3, 2 }, { 1, 0 } } 

DateTimeExtensions

Extension methods for DateTime and TimeSpan. Currently there are just a few.

We are considering adding some ruby'ish DateTime extensions (1, 2) but they look more beautiful than useful in my opinion. How often do you hard code DateTime constants in your code? They usually come from the DB, a config file... Is it worth bloating int Intellisense?

IsInInterval, IsInDateInterval Image

Returns whether a date is in the interval [MinDate, MaxDate[ (max date not included). As usual it follows a C-interval convention.

public static bool IsInInterval(this DateTime date, DateTime minDate, DateTime maxDate)
{
   return minDate <= date && date < maxDate;
}
public static bool IsInInterval(this DateTime date, DateTime minDate, DateTime? maxDate)
{
   return minDate <= date && (maxDate == null || date < maxDate);
}
public static bool IsInInterval(this DateTime date, DateTime? minDate, DateTime? maxDate)
{
   return (minDate == null || minDate <= date) && 
          (maxDate == null || date < maxDate); 
}

Similar but also asserts that all the three arguments have no time part (hours minutes and seconds).

public static bool IsInDateInterval(this DateTime date, DateTime minDate, DateTime maxDate)
public static bool IsInDateInterval(this DateTime date, DateTime minDate, DateTime? maxDate)
public static bool IsInDateInterval(this DateTime date, DateTime? minDate, DateTime? maxDate)

YearTo

Returns how many whole years there are between dates (Not year transitions):

public static int YearsTo(this DateTime min, DateTime max)

It does not takes hours, minutes ... into account.

Example:

new DateTime(1999, 12, 31).YearsTo(new DateTime(2000, 1, 1)); //Returns 0, no whole year
new DateTime(1999, 12, 31).YearsTo(new DateTime(2001, 1, 1)); //Returns 1

MonthsTo

Returns how many whole months there are between Dates (Calendar months, not Days divided by something between 28 and 31, or month transitions).

public static int MonthsTo(this DateTime min, DateTime max)

It does not takes hours, minutes ... into account.

Example:

new DateTime(2009, 2, 4).MonthsTo(new DateTime(2009, 3, 3)); //Returns 0
new DateTime(2009, 2, 4).MonthsTo(new DateTime(2009, 3, 4)); //Returns 1

DateSpanTo and Add

DateSpan is a calendar-relative version of TimeSpan for big time spans (Years, Months, and Days). That means that it's not possible to be transformed to TimeSpan without a calendar context.

public struct DateSpan
{ 
    public readonly int Years;
    public readonly int Months;
    public readonly int Days;

public DateSpan(int years, int months, int days){...} public static DateSpan FromToDates(DateTime min, DateTime max){...} public DateTime AddTo(DateTime date){...} public DateSpan Invert(){...} public override string ToString(){...} }

public static DateSpan DateSpanTo(this DateTime min, DateTime max) public static DateTime Add(this DateTime date, DateSpan dateSpan)

Example:

var cer = new DateTime(1547, 9, 29);
var sha = new DateTime(1564, 4, 26);

DateSpan ds1 = cer.DateSpanTo(sha); // 16 Years, 6 Months, 28 Days DateSpan ds2 = sha.DateSpanTo(cer); // -16 Years, -6 Months, -28 Days

var sha2= cer.Add(ds1); Console.WriteLine(sha == sha2); //true

var cer2 = sha.Add(ds2); Console.WriteLine(cer == cer2); //true


DateSpan.ToString has changed in SF 2.0 to have year(s), month(s) and day(s) correctly pluralized, and avoid writing them when they are zero

new DateSpan(0, 1, 0).ToString(); // returns: "1 Month"

EnumExtensions

Just some extensions for any kind of enum.

ToEnum

Just parses the enum using Enum.Parse, but does the casting for you.

public static T ToEnum<T>(this string str) where T : struct
public static T ToEnum<T>(this string str, bool ignoreCase) where T : struct

Example:

"Monday".ToEnum<DayOfWeek>()); //returns DayOfWeek.Monday
"monday".ToEnum<DayOfWeek>()); //throws ArgumentException
"Monday".ToEnum<DayOfWeek>(true)); //returns DayOfWeek.Monday
"monday".ToEnum<DayOfWeek>(true)); //returns DayOfWeek.Monday

GetValues

Returns all the values in an enum type in a typed array:

public static T[] GetValues<T>()

Example:
EnumExtensions.GetValues<DayOfWeek>();
//Returns: new DayOfWeek[]{DayOfWeek.Sunday, DayOfWeek.Monday, ... }

IsDefined

Just as Enum.IsDefined but saving you to do the typeof(MyEnum)

public static bool IsDefined<T>(T value) where T : struct

Example:

EnumExtensions.IsDefined(DayOfWeek.Monday); //returns true
EnumExtensions.IsDefined((DayOfWeek)10); // returns false

MinFlag and MaxFlag

Returns the minimum flag in a int (useful for enums decorated with FlagsAttribute).

public static int MinFlag(int value)
public static int MaxFlag(int value)

Example:

//Binary representation of 14 = 1110 = 8 + 4 + 2
EnumExtensions.MinFlag(14); //Returns 2
EnumExtensions.MaxFlag(14); //Returns 8  

ListExtensions

Extract

Extracts to a new List all the elements that satisfy a condition, removing them from the original list.

public static List<T> Extract<T>(this IList<T> list, Func<T, bool> condition)

Example:

var nums = new List<int> { 1, 2, 3, 4 };
var odds = nums.Extract(n => n % 2 == 0);
//nums = new ¬List<int> { 1, 3 }
//odds = new ¬List<int> { 2, 4 }

Sort

An in-place list Sort (as opposed to OrderBy) that takes a lambda to the field instead of a IComparer<T> or Comparison<T>.

public static void Sort<T, A>(this List<T> list, Func<T, A> keySelector)

Example:

var nums = new List<DayOfWeek> 
{  
  DayOfWeek.Monday,
  DayOfWeek.Friday,
  DayOfWeek.Saturday, 
  DayOfWeek.Tuesday
};

nums.Sort(a => a.ToString());

//nums is now shorted alphabetically: //new List<DayOfWeek> //{ // ¬DayOfWeek.Friday, // ¬DayOfWeek.Monday, // ¬DayOfWeek.Saturday, // ¬DayOfWeek.Tuesday //};

RemoveAll

Removes all the elements that satisfy a given condition (works over any IList):

public static void RemoveAll<T>(this IList<T> list, Func<T, bool> condition)

Example:

IList<int> nums = new List<int> { 1, 2, 3, 4, 5, 6 };
nums.RemoveAll(a => a % 3 == 0); 
//nums = new List<int> { 1, 2, 4, 5 };

AddRange

Adds many items in one operation (works over any IList):

public static void AddRange<T>(this IList<T> list, IEnumerable<T> elements)
public static void AddRange<T>(this IList<T> list, params T[] elements)

Example:

IList<int> nums = new List<int> { 1, 2 };
nums.AddRange(3,4);
nums.AddRange(6.To(10)); 
//nums = new List<int> { 1, 2, 3, 4, 6, 7, 8, 9 };

ReflectionExtensions

Some extensions to enrich Reflection API. See also ReflectionUtils.

Nullify, UnNullify and IsNullable

Extension methods over System.Type to deal with Nullable Types.

public static bool IsNullable(this Type type)
public static Type Nullify(this Type type)
public static Type UnNullify(this Type type)

Examples:

Type intType = typeof(int);
Console.WriteLine(intType.IsNullable());  //false
Type nIntType = intType.Nullify();
Console.WriteLine(nIntType.IsNullable()); //true
Console.WriteLine(nIntType.UnNullify() == intType); //true

ReturningType

Gets the returning type for a PropertyInfo, FieldInfo, MethodInfo, ConstructorInfo or EventInfo in a... carefree way. Returns null for System.Type (i.e: nested Type).

public static Type ReturningType(this MemberInfo m)

Example:

MemberInfo member = typeof(Person).GetMember(DateTime.Today.Day % 2 == 0 ? "_name" : "Name");
member.ReturningType();
//Returns string type, whether a FieldInfo or a PropertyInfo is retrieved.


HasAttribute and SigleAttribute

Allows to know easily if a MemeberInfo contains attributes of some type and retrieves them (if any).

public static bool HasAttribute<T>(this ICustomAttributeProvider mi) where T : Attribute
public static T SingleAttribute<T>(this ICustomAttributeProvider mi) where T : Attribute

Changed from MemberInfo to ICustomAttributeProvider in SF 2.0, no code should break

Example:

[Serializable]
public class Person
{

}

typeof(Person).HasAttribute<SerializableAttribute>(); //Returns true typeof(Person).SingleAttribute<SerializableAttribute>(); //returns the SerializableAttribute


IsInstantiationOf

Fast way to know if a System.Type represents a 'concretization' of a generic type.
public static bool IsInstantiationOf(this Type type, Type genericType)

Example:

typeof(List<int>).IsInstantiationOf(typeof(List<>)); // returns true 


FieldEquals and PropertyEquals

Simple way to compare a FieldInfo (or PropertyInfo) using Strong Typed Reflection.

public static bool FieldEquals<T>(this FieldInfo fi, Expression<Func<T, object>> lambdaToFiel)
public static bool PropertyEquals<T>(this PropertyInfo fi, Expression<Func<T, object>> lambdaToProperty)

Example:

typeof(string).GetProperty("Length").PropertyEquals((string s) => s.Length); //returns true


IsReadOnly

Returns whether a property has no setter or it's not public.

public static bool IsReadOnly(this PropertyInfo pi)

Example:

typeof(string).GetProperty("Length").IsReadOnly(); //returns true

RegexExtensions

Some methods to make common patterns involving Regex and IEnumerables easier.

Performance Consideration: Creating a Regex object is an expensive operation (have to be parsed and compiled). The methods here cache the object locally, using the same for all the elements in the collection, but not from one call to the next one. This is a good idea for Loading applications, but for server methods it's a better idea to store the Regex object in a static field, not using the methods here.

Match, MatchPair

Applies a Regex string to all the elements in collection, returning only the ones who actually matched.

public static IEnumerable<Match> Match(this IEnumerable<string> collection, string regex)
public static IEnumerable<Match> Match<T>(this IEnumerable<T> collection, Func<T, string> stringSelector, string regex)

public static IEnumerable<Tuple<string, Match>> MatchPair(this IEnumerable<string> collection, string regex) public static IEnumerable<Tuple<T, Match>> MatchPair<T>(this IEnumerable<T> collection, Func<T, string> stringSelector, string regex)

Example:

typeof(Console).Assembly.GetTypes()
.MatchPair(a => a.Name, "^.*Console.*$")
.ToConsole(p => p.First.Name);

//Console //ConsoleCancelEventHandler //ConsoleCancelEventArgs //ConsoleColor //ConsoleKey //ConsoleKeyInfo //ConsoleModifiers //ConsoleSpecialKey //ConsoleCtrlHandlerRoutine //__ConsoleStream


MostSimilar

Uses StringDistance to find the item with the selected string with min string distance to a given pattern.

public static T MostSimilar<T>(this IEnumerable<T> collection, Func<T, string> stringSelector, string pattern)

Example:

typeof(string).Assembly.GetTypes().MostSimilar(a => a.Name, "Quonsole"); //return the System.Console Type object. 
Creative Commons License Signum Framework Site by Signum Software is licensed under a Creative Commons Attribution 3.0 License.
Powered by ScrewTurn Wiki version 3.0.5.600.