WilliamSmithE.Transformer
2.0.0
See the version list below for details.
dotnet add package WilliamSmithE.Transformer --version 2.0.0
NuGet\Install-Package WilliamSmithE.Transformer -Version 2.0.0
<PackageReference Include="WilliamSmithE.Transformer" Version="2.0.0" />
<PackageVersion Include="WilliamSmithE.Transformer" Version="2.0.0" />
<PackageReference Include="WilliamSmithE.Transformer" />
paket add WilliamSmithE.Transformer --version 2.0.0
#r "nuget: WilliamSmithE.Transformer, 2.0.0"
#:package WilliamSmithE.Transformer@2.0.0
#addin nuget:?package=WilliamSmithE.Transformer&version=2.0.0
#tool nuget:?package=WilliamSmithE.Transformer&version=2.0.0
Transformer
Transformer is a set of extension methods for .NET that convert values from one type to another: text to numbers, dates and booleans, one value or a whole collection at a time, and a list of objects to a DataTable you can print.
dotnet add package WilliamSmithE.Transformer
Everything is in the Transformer namespace. The package targets net8.0, net9.0 and net10.0 and has no dependencies.
Convert a value
using Transformer;
int number = "123".ToNonNullableType<int>();
int failed = "123A".ToNonNullableType<int>();
float single = 1.ToNonNullableType<float>();
DateTime date = "2023-01-02".ToNonNullableType<DateTime>();
Console.WriteLine(number); // 123
Console.WriteLine(failed); // 0
Console.WriteLine(single); // 1
Console.WriteLine(date.ToString("yyyy-MM-dd")); // 2023-01-02
int? missing = "123A".ToNullableType<int>();
int? zero = "123A".ToNullableType<int>(false);
int? blank = " ".ToNullableType<int>(false);
Console.WriteLine(missing is null); // True
Console.WriteLine(zero); // 0
Console.WriteLine(blank is null); // True
try
{
"123A".ToNonNullableType<int>(false);
}
catch (InvalidCastException e)
{
Console.WriteLine(e.Message); // Cannot convert value to type System.Int32.
Console.WriteLine(e.InnerException?.GetType().Name); // FormatException
}
Check before converting
using Transformer;
string? text = "123A";
string? nothing = null;
Console.WriteLine("123".IsParseable<int>()); // True
Console.WriteLine(text.IsParseable<int>()); // False
Console.WriteLine(nothing.IsParseable<int>()); // False
Console.WriteLine(nothing.IsParseable<int>(allowNullable: true)); // True
Enums, Guid, TimeSpan and other value types
using Transformer;
Console.WriteLine("friday".ToNonNullableType<DayOfWeek>()); // Friday
Console.WriteLine(5.ToNonNullableType<DayOfWeek>()); // Friday
Console.WriteLine("Funday".IsParseable<DayOfWeek>()); // False
Console.WriteLine("01:30:00".ToNonNullableType<TimeSpan>()); // 01:30:00
Console.WriteLine("2023-01-02".ToNonNullableType<DateOnly>().ToString("yyyy-MM-dd")); // 2023-01-02
Console.WriteLine("0f8fad5b-d9cb-469f-a165-70867728950e".IsParseable<Guid>()); // True
Convert a collection
using Transformer;
var list = new List<string> { "1", "bob", "apple", "2", "3" };
var result = list.ToNonNullableCollectionType<List<string>, string, List<int>, int>();
Console.WriteLine(string.Join(", ", result.TransformationSuccesses)); // 1, 2, 3
Console.WriteLine(string.Join(", ", result.TransformationFailures)); // bob, apple
The four type arguments are the source collection, its element type, the collection to fill and its element type. The result is a CollectionTransformResult<TCollectionNew, TNewType>: TransformationSuccesses holds the converted values in a new TCollectionNew, and TransformationFailures the source elements that did not convert, as a List<object>.
Make a DataTable and print it
using System.Data;
using Transformer;
var people = new List<Person>
{
new() { Name = "Ann", Age = 31 },
new() { Name = "Bob", Age = 4 },
};
DataTable table = people.IEnumerableToDataTable();
Console.WriteLine(table.Columns[1].DataType); // System.Int32
Console.Write(table.ToConsoleString());
// --------------
// | Name | Age |
// --------------
// | Ann | 31 |
// | Bob | 4 |
// --------------
class Person
{
public string Name { get; set; } = "";
public int Age { get; set; }
}
Round a number and title-case a string
using Transformer;
Console.WriteLine(3.14159.Round(2)); // 3.14
Console.WriteLine(2.5.Round(0)); // 2
Console.WriteLine(1.25f.Round(1)); // 1.2
Console.WriteLine("hello NASA".ToTitleCase()); // Hello Nasa
How values convert
ToNonNullableType<T>, ToNullableType<T>, IsParseable<T> and ToNonNullableCollectionType convert in the same way. T must be a value type. For the types Convert.ChangeType knows, the numeric types, bool, char and DateTime, they give the result Convert.ChangeType(value, typeof(T)) gives. They read text with the target type's own TryParse, so text that does not convert costs no exception.
Text is read in the current culture, so the same string can give different numbers and dates on different machines. Each of the four methods has an overload whose first argument is an
IFormatProviderthat reads text instead: passCultureInfo.InvariantCulturefor text written in a fixed format, such as a file or another program's output, or a named culture for text typed in that culture.nullthere means the current culture.using System.Globalization; using Transformer; CultureInfo.CurrentCulture = new CultureInfo("en-US"); Console.WriteLine("1,5".ToNonNullableType<double>()); // 15 Console.WriteLine("1/2/2023".ToNonNullableType<DateTime>().ToString("yyyy-MM-dd")); // 2023-01-02 CultureInfo.CurrentCulture = new CultureInfo("de-DE"); Console.WriteLine("1.5".ToNonNullableType<double>()); // 15 Console.WriteLine("1/2/2023".ToNonNullableType<DateTime>().ToString("yyyy-MM-dd")); // 2023-02-01 var invariant = CultureInfo.InvariantCulture; Console.WriteLine("1.5".ToNonNullableType<double>(invariant).ToString(invariant)); // 1.5 Console.WriteLine("1.5".IsParseable<decimal>(invariant)); // True Console.WriteLine("x".ToNullableType<int>(invariant, false)); // 0 var list = new List<string> { "1.5", "2.5" }; var result = list.ToNonNullableCollectionType<List<string>, string, List<double>, double>(invariant); Console.WriteLine(result.TransformationSuccesses.Sum().ToString(invariant)); // 4Text converts to a whole-number type only when it is a whole number: "1.5" and "1,000" do not convert to
int. Adoubledoes convert, rounded to the nearest even number, so 1.5 and 2.5 both give 2.A value outside the range of
T, such as "300" forbyte, does not convert.Text converts to
boolonly as "true" or "false", in any case. "1" and "yes" do not convert; the number 1 converts totrue.nullandDBNull.Valuedo not convert.An enum converts from its name, in any case, or from a whole number, as text or as a value of an integer type. Like any enum, it takes a number it has no name for: "42" gives
(DayOfWeek)42. A name it does not have, a fraction, a number too large for it and a value of another enum type do not convert.Other value types with a public static
TryParse(string, IFormatProvider, out T), such asGuid,TimeSpan,DateTimeOffset,DateOnly,TimeOnly,Int128andBigInteger, convert from text, read by thatTryParsein the current culture, and from a value that already has the type. A number does not convert to them.ToNonNullableType<T>()returnsdefault(T)(0,false,DateTime.MinValue) when the value does not convert.ToNonNullableType<T>(false)throwsInvalidCastExceptioninstead, whoseInnerExceptionis the cause: aFormatExceptionfor text that does not parse as that type, anOverflowExceptionfor a value out of its range, anArgumentExceptionfor a name an enum does not have, or anInvalidCastExceptionfornullor a type that does not convert.ToNullableType<T>()returnsnullfornull,DBNull.Value, an empty string and a string of spaces, whatever its argument. For any other value that does not convert it returnsnull, ordefault(T)withToNullableType<T>(false).IsParseable<T>()returns whether the conversion would succeed. It returnsfalsefornull,DBNull.Value, an empty string and a string of spaces, andtruefor them withallowNullable: true. Because a space counts as blank," ".IsParseable<char>()isfalseand" ".ToNullableType<char>()isnull, while" ".ToNonNullableType<char>()returns the space.
Collections
ToNonNullableCollectionTypekeeps the source order.TCollectionNewneeds a public parameterless constructor, and itsAdddecides what is kept: aHashSet<int>keeps one of each value.- An empty string or a string of spaces does not convert, so it goes to
TransformationFailures. Anullelement is left out of both lists.
DataTables
IEnumerableToDataTable<T>()makes one column for each public instance property ofTthat has a public getter, in the order reflection returns them, which is in practice the order they are declared. Static properties, indexers and properties without a public getter are left out, and a property hidden withnewgives one column, from the most derived type. The column is named after the property and has its type, or the underlying type for aNullable<>property, whosenullbecomesDBNull.Value.- Each element becomes one row; a
nullelement becomes a row ofDBNull.Value. Anulllist throwsArgumentNullException. - The columns come from
T, the element type the list is declared with, not from the type of each element. The table is named afterT's full name. A list of strings gives one column,Length, and a list of numbers gives none, because those are the types' public properties. ToConsoleString()writes the table as text: a header row of column names and one row per data row, each column as wide as its longest value, values written withToString()in the current culture. A value with a line break in it breaks the layout. Anulltable throwsArgumentNullException.
Rounding and text
Round(digits)on adoubleisMath.Round(value, digits): a value halfway between two results goes to the even one, so2.5.Round(0)is 2 and3.5.Round(0)is 4.- On a
floatit rounds the value as adoubleand converts back. Afloatholds most decimals inexactly, so1.005f.Round(2)is 1, because 1.005f is stored as 1.00499999523. digitsmust be 0 to 15, orRoundthrowsArgumentOutOfRangeException.ToTitleCase()lower-cases the whole string, then capitalizes the first letter of each word, so acronyms are lower-cased too: "hello NASA" gives "Hello Nasa", and "o'neil mcdonald-smith" gives "O'neil Mcdonald-Smith". Both steps use the invariant culture, so the result is the same on every machine, Turkish ones included. Anullstring throwsArgumentNullException.
Attributions
Icon "Transformer.png" designed by Icon home on Freepik.com.
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- No dependencies.
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.