-
Notifications
You must be signed in to change notification settings - Fork 157
DataTypes Namespace
DataTypes is, well, rather large. It contains a couple hundred extension methods, helper classes, a data mapper, data type converter, code generation, AOP system, etc. So I'm not going to cover everything in here but I will cover the big things:
Along with the items above there are a number of extension methods (a couple hundred anyway). In order to use them simply add:
using Utilities.DataTypes;
With that you've added a number of extension methods.
Array Extensions
Clear:
int[] MyArray=new int[]{1,2,3,4,5};
MyArray.Clear(); //MyArray is empty after this call
Concat:
int[] Array1=new int[]{1,2,3,4,5};
int[] Array2=new int[]{6,7,8,9,10};
int[] Array3=new int[]{11,12,13,14,15};
int[] FinalArray=Array1.Concat(Array2,Array3); //FinalArray will contain the numbers 1 through 15
DateTime Extension
AddWeeks:
DateTime Result=DateTime.Now.AddWeeks(-1); //This returns the day one week ago.
Age:
int Result=new DateTime(1900,1,1).Age(new DateTime(2000,1,1)); //The result is the number of years difference between the two dates (100)
BeginningOf:
DateTime BeginningOfWeek=DateTime.Now.BeginningOf(TimeFrame.Week); //Gets the beginning of the week
DateTime BeginningOfDay=DateTime.Now.BeginningOf(TimeFrame.Day); //Gets the beginning of the day
DateTime BeginningOfMonth=DateTime.Now.BeginningOf(TimeFrame.Month); //Gets the beginning of the month
DateTime BeginningOfQuarter=DateTime.Now.BeginningOf(TimeFrame.Quarter,new DateTime(2010,1,1)); //Gets the beginning of the quarter. It defines the beginning of quarter 1 as 1/1/2010.
DateTime BeginningOfYear=DateTime.Now.BeginningOf(TimeFrame.Year); //Gets the beginning of the year
DaysIn:
int NumberOfDays=DateTime.Now.DaysIn(TimeFrame.Month); //Gets the number of days in the month. It uses the same TimeFrame enum as BeginningOf and thus can do week, month, year, etc.
DaysLeftIn:
int DaysLeft=DateTime.Now.DaysLeftIn(TimeFrame.Month); //Gets the number of days left in the month.
EndOf:
DateTime EndOfWeek=DateTime.Now.EndOf(TimeFrame.Week); //Gets the end of the week
DateTime EndOfDay=DateTime.Now.EndOf(TimeFrame.Day); //Gets the end of the day
DateTime EndOfMonth=DateTime.Now.EndOf(TimeFrame.Month); //Gets the end of the month
DateTime EndOfQuarter=DateTime.Now.EndOf(TimeFrame.Quarter,new DateTime(2010,1,1)); //Gets the end of the quarter. It defines the end of quarter 1 as 1/1/2010.
DateTime EndOfYear=DateTime.Now.EndOf(TimeFrame.Year); //Gets the end of the year
Is:
bool Result=DateTime.Now.Is(DateCompare.InFuture); //Determines if this is in the future or not
bool Result=DateTime.Now.Is(DateCompare.InPast); //Determines if this is in the past or not
bool Result=DateTime.Now.Is(DateCompare.Today); //Determines if this is in today or not
bool Result=DateTime.Now.Is(DateCompare.WeekDay); //Determines if this is a week day or not
bool Result=DateTime.Now.Is(DateCompare.WeekEnd); //Determines if this is a week end or not
LocalTimeZone:
TimeZoneInfo LocalTimeZone=DateTime.Now.LocalTimeZone(); //Gets the local time zone information
SetTime:
DateTime Result=DateTime.Now.SetTime(11,0,0); //Sets the time to 11:00:00 AM
DateTime Result=DateTime.Now.SetTime(new TimeSpan(11,0,0)); //Sets the time to 11:00:00 AM
To:
DateTime Result=DateTime.Now.To(TimeZoneInfo.Utc); //Converts the DateTime to UTC
int UnixTime=DateTime.Now.To(); //Converts the DateTime to Unix time
DateTime Result=15734894.To(); //Converts from Unix time to a DateTime object
ToString:
string Result=DateTime.Now.ToString(new DateTime.Now.AddDays(-1)); //Returns "1 day from now"
UTCOffset:
double Offset=DateTime.Now.UTCOffset(); //Gets the UTC offset for the DateTime object
Delegate Extensions
Async:
new Action(()=>{ ... }).Async(); //This starts the action in a new thread.
Raise:
new Func<int,int>(x=>x).Raise(); //This safely runs the Func (useful if you don't know if it's null, etc).
Exception Extensions
ToString:
new Exception("Example message").ToString("Error occurred within the application:");
The above outputs a string version of the Exception. It includes the exception message, type, data, stack trace, source, target site, etc. Useful mostly for logging purposes.
Generic Object Extensions
Chain:
MyObject.Chain(x=>x.Function(),100); //This check if MyObject is null, if it is not it runs the Func/Action provided. If it is, it returns the default value supplied.
Execute:
new Func<int>(()=>5).Execute(); //This will attempt to run the Func multiple times. Really only useful when you expect the Func may fail.
Check:
Object.Check(new ClassType()); //This checks if the object is null and if it is, returns the default value provided.
You may also specify a predicate to check against the object instead of the default of checking if it is null.
Is:
bool Result=5.Is(x=>x>5); //Check the value against the predicate, returning the result.
bool Result=5.Is(5); //Checks if the value is equal to the object specified.
Times:
IEnumerable<string> Result=10.Times(x=>x.ToString()); //This will run the Func 10 times, outputting the numbers 1 through 10 as strings
ICollection Extensions
Add:
List<int> ExampleList=new List<int>().Add(new int[]{1,2,3,4,5}); //This would add 1 through 5 to the list
AddAndReturn:
List<int> ExampleList=new List<int>();
int ItemAdded=ExampleList.AddAndReturn(10); //Adds 10 to the list and returns that value
AddIf:
List<int> ExampleList=new List<int>();
ExampleList.AddIf(x=>x>5,2,5,6,10); //This would add the values 6 and 10 to the list but not 5 or 2 as they don't pass the predicate specified
AddIfUnique:
List<int> ExampleList=new List<int>();
ExampleList.AddIfUnique(1,2,2,3); //This would add 1,2,3 to the list. The second 2 would not be added as it is already in the list
Remove:
List<int> ExampleList=new List<int>();
ExampleList.Remove(x=>x<2); //This would remove all values that are less than 2 from the list
IComparable Extensions
Between:
5.Between(1,10); //This would return true as it is between 1 and 10
1.Between(1,10); //This would also return true as it the limits are inclusive
Clamp:
10.Clamp(1,5); //This would return 5 for the value as 10 is outside the bounds specified
Max/Min:
10.Max(5); //This would return 10 as it is greater than 5
10.Min(5); //This would return 5 as it is less than 10
IDictionary Extensions
GetValue:
Dictionary<string,string> ExampleDictionary=new Dictionary<string,string>();
string Value=ExampleDictionary.GetValue("ExampleKey","Default Value"); //This safely gets the value from the dictionary using the key specified and if it is not found, returns the default value specified
SetValue:
Dictionary<string,string> ExampleDictionary=new Dictionary<string,string>();
ExampleDictionary.SetValue("ExampleKey","Value to set"); //This safely sets the value for the dictionary using the key specified
Sort:
Dictionary<string,string> ExampleDictionary=new Dictionary<string,string>();
IDictionary<string,string> SortedDictionary=ExampleDictionary.Sort(); //This sorts the dictionary based on the key value. A Func can be sent in to specify what should be used to set the sorting
IEnumerable Extensions
Permute:
ListMapping<int,int> Result=new int[]{1,2,3,4,5,1,2,3}.Permute(); //This finds all permutations of the list
Concat:
IEnumerable<int> Result=new List<int>().Concat(new int[]{1,2,3},new int[]{4,5,6},new int[]{7,8,9}); //The resulting list would contain the values 1 through 9
Distinct:
IEnumerable<int> Result=new int[]{1,2,3,4,5,1,2,3}.Distinct((x,y)=>x!=y); //This would actually return a list containing {1,1} as the predicate is actually doing inequality instead of equality
ElementsBetween:
IEnumerable<int> Result=new int[]{1,2,3,4,5,6,7,8,9}.ElementsBetween(5,8); //This would return {6,7,8,9} as it is returning values between index 5 and index 8
For:
IEnumerable<int> Result=new int[]{1,2,3,4,5,6,7,8,9}.For(0,5,x=>x+1); //This will return {2,3,4,5,6,7,7,8,9} as it runs the function specified for the first 6 items
ForEach:
IEnumerable<int> Result=new int[]{1,2,3,4,5,6,7,8,9}.ForEach(x=>x+1); //This will return {2,3,4,5,6,7,8,9,10} as it runs the function on each item and returns the result
Last:
IEnumerable<int> Result=new int[]{1,2,3,4,5,6,7,8,9}.Last(3); //This will return {7,8,9}
PositionOf:
int Result=new int[]{1,2,3,4,5,6,7,8,9}.PositionOf(6); //This will return 5
Except:
IEnumerable<int> Result=new int[]{1,2,3,4,5,6,7,8,9}.Except(x=>x>6); //This will return {1,2,3,4,5,6}
ToArray:
string[] Result=new int[]{1,2,3,4,5,6,7,8,9}.ToArray(x=>x.ToString()); //This will return {"1","2","3","4","5","6","7","8","9"}
To:
DataTable Result=new ExampleClass[]{new ExampleClass(),new ExampleClass(),new ExampleClass()}.To("Property1","Property2","Property3"); //This will return a DataTable containing 3 rows (one for each object) using the columns, Property1, Property2, and Property3 which will contain the value of the properties that match on the objects.
ToList:
List<string> Result=new int[]{1,2,3,4,5,6,7,8,9}.ToList(x=>x.ToString()); //This will return {"1","2","3","4","5","6","7","8","9"}
ToString:
string Result=new int[]{1,2,3,4,5,6,7,8,9}.ToString(x=>x.ToString(),"|"); //This will return "1|2|3|4|5|6|7|8|9"
Math Extensions
Absolute:
-5.Absolute(); //This will return 5
Exp:
5.Exp(5); //Returns the exponential value (742.065796)
Factorial:
8.Factorial(); //Returns the factorial value (40320)
GreatestCommonDenominator:
9.GreatestCommonDenominator(12); //Returns the greatest common denominator for 9 and 12 (3)
Log:
5.Log(); //Returns the log value (0.698970004)
Median:
new int[] { 9, 11, 10 }.Median(); //This returns 10 as that is the median
Mode:
new int[] { 5, 2, 20, 5, 20, 8, 9, 20, 10 }.Mode(); //This returns 20 as it is the mode
Pow:
4.Pow(4); //This returns 256
Round:
4.0124.Round(3); //This will return 4.012
StandardDeviation:
new double[] { 5, 4, 2, 4, 7, 9, 1, 2, 0 }; //This returns a value between 2.73 and 2.74
Sqrt:
4.Sqrt(); // This returns 2
Variance:
new double[] { 5, 4, 2, 4, 7, 9, 1, 2, 0 }.Variance(); //This returns between 7.5 and 7.6
Predicate Extensions
AddToSet:
Predicate<T> Result=new Predicate<int>(x=>x>5).AddToSet(0); //The new predicate checks if the value is above 5 or 0.
CartesianProduct:
Func<int,int,bool> Result=new Predicate<int>(x=>x>5).CartesianProduct(new Predicate<int>(x=>x<-5)); //This returns a func that checks if value 1 is above 5 and value 2 is below -5
Difference:
Predicate<int> Result=new Predicate<int>(x=>x>5).Difference(new Predicate<int>(x=>x<10)); //This returns a predicate that is true for items 10 or above.
Intersect:
Predicate<int> Result=new Predicate<int>(x=>x>5).Intersect(new Predicate<int>(x=>x<10)); //This returns a predicate that is true for values between 5 and 10
RelativeComplement:
Predicate<int> Result=new Predicate<int>(x=>x>5).RelativeComplement(new Predicate<int>(x=>x==6)); //This returns a predicate that is true for values above 5 except for 6
RemoveFromSet:
Predicate<int> Result=new Predicate<int>(x=>x>5).RemoveFromSet(10); //Returns a predicate that is true for values above 5 except 10
Union:
Predicate<int> Result=new Predicate<int>(x=>x>5).Union(new Predicate<int>(x=>x<5)); //Returns a predicate that is true for all values except 5
Process Extensions
KillProcessAsync:
Process.GetProcesses().KillProcessAsync(); //Don't run this but it kills all processes that you give it.
GetInformation:
string ProcessInfo=Process.GetProcesses().GetInformation(); //Exports process information as a string
Reflection Oriented Extensions
Attribute:
MyAttribute Result=typeof(MyClass).Attribute<MyAttribute>(); //Gets the first attribute of the type specified associated with the MyClass type
Attributes:
IEnumerable<MyAttribute> Result=typeof(MyClass).Attributes<MyAttribute>(); //Gets all attributes of the type specified associated with the MyClass type
Call:
object Value=new MyClass();
string Result=Value.Call("ToString"); //Calls the ToString method on Value and returns the result
Create:
MyClass Result=typeof(MyClass).Create(); //Creates an object of the type specified
GetName:
string TypeName=typeof(IEnumerable<MyClass>).GetName(); //Gets the proper C# name of the class, including namespace information.
HasDefaultConstructor:
bool Result=typeof(MyClass).HasDefaultConstructor(); //Determines if the class has a default constructor and returns true if it does, false otherwise
Is:
bool Result=typeof(MyClass).Is<IMyInterface>(); //Determines if the Type inherits from IMyInterface
bool Result=new MyClass().Is<IMyInterface>(); //Determines if the class inherits from IMyInterface
Load:
Assembly Result=AssemblyName.GetAssemblyName("DLL_Location.dll").Load(); //Loads the assembly into the current domain and returns the assembly
LoadAssemblies:
IEnumerable<Assembly> Result=new DirectoryInfo("Location").LoadAssemblies(); //Loads all DLLs found in the directory
MarkedWith:
IEnumerable<Type> Result=new Type[]{typeof(MyClass1),typeof(MyClass2),typeof(MyClass3)}.MarkedWith<MyAttribute>(); //Determines which of the types are marked with a specified attribute
Objects:
IEnumerable<IMyInterface> Result=AppDomain.CurrentDomain.GetAssemblies().Objects<IMyInterface>(); //Gets all classes from the currently loaded assemblies that inherit from IMyInterface and creates an instance of them.
Types:
IEnumerable<Type> Result=AppDomain.CurrentDomain.GetAssemblies().Types<IMyInterface>(); //Gets all classes from the currently loaded assemblies that inherit from IMyInterface and returns their types.
Stream Extensions
ReadAllBinary:
byte[] Result=new MemoryStream().ReadAllBinary(); //Gets everything from the stream and returns it as a byte array.
ReadAll:
string Result=new MemoryStream().ReadAll(); //Gets everything from the stream and returns it as a string
String Extensions
Note that most of the string extensions will allow you to specify the CultureInfo that you would like to use. By default most of them use CultureInfo.Current.
AppendLineFormat:
new StringBuilder().AppendLineFormat("This is test number {0}", 1); //Adds a line saying "This is test number 1"
Center:
"Example".Center(11,"*"); //This would return "**Example**"
Encode:
"ExampleText".Encode(Encoding.ASCII,Encoding.UTF32); //This converts the string from ASCII to UTF32.
FromBase64:
string Result="QVNERg==".FromBase64(Encoding.ASCII); //This returns "ASDF"
byte[] Result="QVNERg==".FromBase64(); //This converts the base64 string to a byte array
Is:
"\u25EF\u25EF\u25EF".Is(StringCompare.Unicode); //This checks if the string is unicode
"4408041234567893".Is(StringCompare.CreditCard); //Checks if the number is a valid credit card number
"debit card".Is("bad credit",StringCompare.Anagram); //Checks if the strings are anagrams of each other
Keep:
"The brown fox is awesome. But the blue fox is not".Keep("fox"); //Does a regex check and only keeps the matches from the string. In this case it returns "foxfox"
"Example number 1".Keep(StringFilter.Alpha); //This only keeps alpha characters. So it returns "Example number "
"Example number 1".Keep(StringFilter.Numeric); //This keeps only the numeric characters. So it returns "1"
"Example number 1".Keep(StringFilter.Alpha|StringFilter.Numeric); //This keeps both the alpha and numeric characters, thus returning the original string
Left:
"This is an example".Left(4); //This returns the first 4 characters in the string "This"
LevenshteinDistance:
"Test".LevenshteinDistance("Testing"); //This would return 3 as there are only 3 letters that are different
MaskLeft:
"This is an example".MaskLeft(4,"*"); //This would mask the first 4 characters in the string. "**** is an example"
MaskRight:
"This is an example".MaskRight(4,"*"); //This would mask the last 4 characters in the string. "This is an exa****"
NumberTimesOccurs:
"The brown fox is awesome. But the blue fox is not".NumberTimesOccurs("is"); //This counts the number of times that the regex specified occurs in the string. In this case, 2.
Pluralize:
"child".Pluralize(); //This pluralizes the string. So in this case it returns "children"
Remove:
"The brown fox is awesome. But the blue fox is not".Remove("fox"); //Does a regex check and removes the matches from the string. In this case it returns "The brown is awesome. But the blue is not."
"Example number 1".Remove(StringFilter.Alpha); //This removes the alpha characters. So it returns "1"
"Example number 1".Remove(StringFilter.Numeric); //This removes the numeric characters. So it returns "Example number "
"Example number 1".Remove(StringFilter.Alpha|StringFilter.Numeric); //This removes both the alpha and numeric characters, thus returning an empty string.
Replace:
"This is a test.".Replace(StringFilter.ExtraSpaces, " "); //This removes the extra spaces from the string and returns "This is a test."
Reverse:
" this is a test".Reverse(); //This reverses the string and would return "tset a si siht "
Right:
"This is an example".Right(7); //This returns the last 7 characters in the string. So this returns "example"
Singularize:
"children".Singularize(); //This singularizes the string. This example would return "child"
StripLeft:
"{{{{{ASDF}}}}}}".StripLeft("{A"); //This strips out all characters that are found in the characters specified until a character not specified is found. In this case it strips out the '{' and 'A' characters. Thus returning "SDF}}}}}}".
StripRight:
"{{{{{ASDF}}}}}}".StripRight("}F"); //This strips out all characters that are found in the characters specified until a character not specified is found, starting from the right. In this case it strips out the '}' and 'F' characters. Thus returning "{{{{{ASD".
ToByteArray:
"This is an example".ToByteArray(); //This would convert the string to a byte array.
ToString:
"This is an example".ToString(Base64FormattingOptions.None); //This converts the string to a Base64 string using the Base64FormattingOptions.None setting.
"this is an example".ToString(StringCase.FirstCharacterUpperCase); //This would change the string, capitalizing the first character in the string. Thus returning "This is an example".
"this is an example".ToString(StringCase.TitleCase); //This would change the string, changing it to title case. Thus returning "This is an Example".
"5555555555".ToString("(###)###-####"); //This formats the string, returning it based on the format specified (# are numbers, @ are alpha characters). This would return (555)555-5555.
"<A>{A}</A><B>{B}</B><C>{C}</C>".ToString(new MyClass()); //This takes the properties from the object sent in and replaces the corresponding name between '{' and '}' (you can change these) with the value from the property.
"This is an example".ToString(new KeyValuePair("This","That"),new KeyValuePair("is","was")); //This replaces a series of items within the string based on the KeyValuePairs specified. In the example, it returns "That was an example".
TimeSpan Extensions
DaysRemainder:
(new DateTime(2011, 12, 1) - new DateTime(1977, 1, 1)).DaysRemainder(); //This returns the number of days after taking out the months and years from the TimeSpan. This example returns 0.
Months:
(new DateTime(2011, 12, 1) - new DateTime(1977, 1, 1)).Months(); //This returns the number of months within the TimeSpan minus the years. The above returns 11.
Years:
(new DateTime(2011, 12, 1) - new DateTime(1977, 1, 1)).Years(); //This returns the number of years within the TimeSpan. This example returns 34.
ToStringFull:
(new DateTime(2011, 12, 1) - new DateTime(1977, 1, 1)).ToStringFull(); //This returns the TimeSpan as a nice string. This example returns "34 years, 11 months".
Average:
new TimeSpan[] { new TimeSpan(10), new TimeSpan(30) }.Average(); //This averages the TimeSpans and returns a new TimeSpan with the average of the list. The example would return new TimeSpan(20).
Type Conversion Extensions
To:
This extension is very powerful and lets you basically convert any type to really any other type. It does this by first checking if there is a direct conversion available using the built in data conversion system. If one does not exist, it creates a new instance of the desired type and copies properties over that match using the built in data mapper system. Both the data mapper and data conversion systems can be tied into and new mappings/conversions added as they are needed.
new DataTable().To(()=>new MyClass()); //This converts a DataTable to a list of objects. It also allows you to define how each of those objects are created.
int Value="5".To(0); //This is a very generic extension that will convert from almost any type to almost any other type. For example the above would convert the string 5.
MyClass2 Result=new MyClass().To(); //This will attempt to see if MyClass can be converted to a MyClass2. If not, it will create a new MyClass2 and copy over properties that match.
Value Type Extensions
ToString:
new byte[]{50,50,50}.ToString(Base64FormattingOptions.None); //This converts the byte array to a Base64 string using the options specified.
new byte[]{50,50,50}.ToString(Encoding.ASCII); //This converts the byte array to a string using the encoding specified.
There are more extension methods that I did not list above. Also as time goes on, I'm sure that more will be added that are not listed here. So check out the Utilities.DataTypes namespace for more.