Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save martincostello/57bf28200b1d9ab9619c151c532cef83 to your computer and use it in GitHub Desktop.
Save martincostello/57bf28200b1d9ab9619c151c532cef83 to your computer and use it in GitHub Desktop.
An extension method to turn a string into a sequence of numbers using .NET 6 Generic Math
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
<ImplicitUsings>enable</ImplicitUsings>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Shouldly" Version="4.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../AsNumbers/AsNumbers.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3" />
</ItemGroup>
</Project>
using Shouldly;
using Xunit;
namespace AsNumbers.Tests;
public static class Tests
{
[Fact]
public static void Convert_Strings_To_Number_Sequences()
{
"1,2,3".AsNumbers<int>().ShouldBe(new[] { 1, 2, 3 });
"1 2 3".AsNumbers<uint>(' ').ShouldBe(new[] { 1U, 2U, 3U });
"1 2 3".AsNumbers<long>(' ').ShouldBe(new[] { 1L, 2L, 3L });
"1 2 3".AsNumbers<ulong>(' ').ShouldBe(new[] { 1UL, 2UL, 3UL });
"1.2|3.4|5.6".AsNumbers<float>('|').ShouldBe(new[] { 1.2F, 3.4F, 5.6F });
"1.2,,3.4".AsNumbers<double>(options: StringSplitOptions.RemoveEmptyEntries).ShouldBe(new[] { 1.2D, 3.4D });
"".AsNumbers<int>(options: StringSplitOptions.RemoveEmptyEntries).ShouldBe(Array.Empty<int>());
"1.2,3.4".AsNumbers<decimal>().ShouldBe(new[] { 1.2M, 3.4M });
"1,2,3".AsNumbers<ushort>().ShouldBe(new ushort[] { 1, 2, 3 });
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EnablePreviewFeatures>true</EnablePreviewFeatures>
<ImplicitUsings>enable</ImplicitUsings>
<OutputType>Library</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Runtime.Experimental" Version="6.0.0" />
</ItemGroup>
</Project>
using System.Globalization;
namespace System;
public static class StringExtensions
{
public static IEnumerable<T> AsNumbers<T>(
this string value,
char separator = ',',
StringSplitOptions options = StringSplitOptions.None,
NumberStyles style = NumberStyles.Any)
where T : INumber<T>
=> value.Split(separator, options).Select(x => T.Parse(x, style, CultureInfo.InvariantCulture));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment