Skip to content

Instantly share code, notes, and snippets.

@imgen
imgen / Anonymous type with Expression.cs
Created August 31, 2021 06:20 — forked from leandromoh/Anonymous type with Expression.cs
Anonymous extension method that allow create a new instance of anonymous with new values, similar to with expression of records in C# and F#
public static class AnonymousExtension
{
static void Main(string[] args)
{
var person = new { FirstName = "Scott", LastName = "Hunter", Sex = 'M', Age = 25 };
var otherPerson = person.With(new { LastName = "Hanselman" });
Console.WriteLine(otherPerson);
}
@imgen
imgen / ManipulateExpressionTrees.cs
Last active June 28, 2021 05:02
Get ride of `Compile` method in the expression trees, can be used to avoid Client Side Evaluations (EF Core 2.x) or InvalidOperation exception (EF Core 3+) when used with Entity Framework Core
// From below CodeProject article
// https://www.codeproject.com/Articles/894936/Manipulate-your-expression-trees-with-elegance
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace ManipulateExpressionTrees
{
public static class ReflectionHelpers
@imgen
imgen / SplitOnCamelCase.cs
Created May 4, 2020 06:13
Split on camel case
// Taken from https://codereview.stackexchange.com/a/133709/209350
var words =
Regex.Matches("SmallFireBall", @"([A-Z][a-z]+)")
.Cast<Match>()
.Select(m => m.Value);
var withSpaces = string.Join(" ", words);
@imgen
imgen / GetTableColumnsSchema.cs
Created March 18, 2020 06:33
The columns metadata of a table
using var conn = new SqlConnection(connectionString);
var connectionStringInfo = new SqlConnectionStringBuilder(connectionString);
var dbName = connectionStringInfo.InitialCatalog;
var sql = $"SELECT * FROM {tableName} WHERE 1 = 2";
using var command = new SqlCommand(sql, conn);
conn.Open();
using var reader = await command.ExecuteReaderAsync(CommandBehavior.KeyInfo);
var columnSchema = reader.GetColumnSchema();
@imgen
imgen / ExportDataTableToCsvFile.cs
Created March 17, 2020 08:58
Export DataTable to CSV File
public static void ToCSV(this DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
@imgen
imgen / OpenWithDefaultProgram.cs
Created March 17, 2020 08:07
Open File With Default Program
public static void OpenWithDefaultProgram(string path)
{
Process fileopener = new Process();
fileopener.StartInfo.FileName = "explorer";
fileopener.StartInfo.Arguments = "\"" + path + "\"";
fileopener.Start();
}
@imgen
imgen / FirstDuplicateFinderPerfTestResult.txt
Last active March 17, 2020 03:19
First Duplicate Finder Perf Test Result
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------------------------------- |-----------:|---------:|---------:|-----------:|------:|------:|------:|-------------:|
| NoDuplicate | 1,178.0 ms | 23.31 ms | 49.17 ms | 1,154.3 ms | - | - | - | - |
| DuplicateInTheMiddle | 556.9 ms | 11.49 ms | 14.53 ms | 558.1 ms | - | - | - | - |
| NoDuplicateWithDictionary | 1,235.6 ms | 22.21 ms | 18.54 ms | 1,236.3 ms | - | - | - | 1000000024 B |
| DuplicateInTheMiddleWithDictionary | 610.1 ms | 11.60 ms | 12.41 ms | 609.6 ms | - | - | - | 1000000024 B |
Use number as index
| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated |
@imgen
imgen / FindFirstDuplicate.cs
Last active March 15, 2020 03:30
A C# solution to the problem of finding first duplicate - an Google interview question
// Original question described in this video
// https://www.youtube.com/watch?v=XSdr_O-XVRQ
public int FindFirstDuplicate(int[] numbers)
{
for(int i = 0; i < numbers.Length; i++)
{
var number = numbers[i];
if (number < 0)
{
@imgen
imgen / NamedFormat.cs
Created March 12, 2020 03:35
A simple named format implementation
public static string NamedFormat(string format, params object[] args)
{
var newFormat = string.Empty;
var paraIndex = 0;
var paraNameIndexMap = new Dictionary<string, int>();
for (int i = 0; i < format.Length; i++)
{
var ch = format[i];
if (ch == '{')
{
public static string FormatTimeSpan(TimeSpan timeSpan)
{
var (minutes, seconds, milliseconds, microseconds) = (
(int)timeSpan.TotalMinutes,
timeSpan.Seconds,
timeSpan.Milliseconds,
int.Parse(timeSpan.ToString("ffffff").Substring(3))
);
return $"{minutes}m {seconds}s {milliseconds}ms {microseconds}μs";