Why isn't this in STL?
template<typename Range, typename Pred> void erase_if(Range& range, Pred&& predicate) { for (auto pos {cbegin(range)}, last {cend(range)}; pos != last; (pos = range.erase(pos)) : ++pos); }
NASA

ellievsbear

#extradirty
I'd rather be in outer space 🛸
Monterey Bay Aquarium

@theartofmadeline
2025 on Tumblr: Trends That Defined the Year
Sweet Seals For You, Always

roma★
Xuebing Du

oozey mess
Acquired Stardust
Aqua Utopia|海の底で記憶を紡ぐ

PR's Tumblrdome
🪼
styofa doing anything
RMH
d e v o n
KIROKAZE

seen from Malaysia

seen from T1

seen from T1
seen from United States

seen from Malaysia

seen from Australia
seen from Australia
seen from United States
seen from Peru

seen from United States

seen from United States
seen from Brazil

seen from Australia
seen from United States
seen from United States
seen from United States

seen from United States

seen from Singapore

seen from United States

seen from Malaysia
@adventureswithdotnet
Why isn't this in STL?
template<typename Range, typename Pred> void erase_if(Range& range, Pred&& predicate) { for (auto pos {cbegin(range)}, last {cend(range)}; pos != last; (pos = range.erase(pos)) : ++pos); }

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
List stable sort
Not necessarily the fastest thing out there:
class StableComparer<T> : IComparer<T> { private readonly Func<T, IComparable> value; private readonly Func<T, IComparable> order; public StableComparer(Func<T, IComparable> valueSelector, Func<T, IComparable> orderSelector) { value = valueSelector; order = orderSelector; } int IComparer<T>.Compare(T x, T y) => value(x).CompareTo(value(y)).Then(result => result != 0 ? result : order(x).CompareTo(order(y))); } ... collection.Sort(new StableComparer<Item>(item => item.Timestamp, item => item.Id));
Multiplying TimeSpans
As in time periods:
static TimeSpan Multiply(this TimeSpan span, int multiplier) => TimeSpan.FromTicks(span.Ticks * multiplier);
Dictionary's GetValueOrDefault
Why isn't it already available?
static V GetValueOrDefault<K, V>(this Dictionary<K, V> source, K key) { V value; source.TryGetValue(key, out value); return value; }
Weighted mean
static double Average<T>(this IEnumerable<T> source, Func<T, double> selector, Func<T, long> weightSelector) => source.Sum(item => selector(item) * weightSelector(item)) / source.Sum(weightSelector);

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Enums as collection
When you need to iterate them:
static IEnumerable<T> GetEnums<T>() => Enum.GetValues(typeof(T)).Cast<T>();
Safe navigation
C# 6 has the ?. operator, but in case earlier versions must be supported:
static U Then<T, U>(this T source, Func<T, U> predicate) => source == null ? default(U) : predicate(source);
Solving Sudoku in F#
Came across this Sudoku solver by Peter Norvig and decided to rewrite in F# (+fsharpx) loosely based on the listed C# one by Richard Birkby:
open FSharpx;open FSharpx.Collections;open System.IO module S=Seq module M=Map let ᶺ=Option.bind let ᵒ i=S.exists((=)i) let ᴓ i=S.filter((<>)i) let Ѧ c=S.length c/3|>(fun l->[S.take l c;S.skip l c|>S.take l;S.skip(l*2)c]) let ₓ a=S.lift2 tuple2 a let α=['1'..'9'] let Ͳ=ₓ α α let ɱ p=S.collect p Ͳ|>S.groupBy fst|>M.ofSeq|>M.map(fun _->S.map snd) let ʋ=ɱ(fun s->S.concat[S.map(fun c->ₓ α [c])α;S.map(fun r->ₓ[r]α)α;S.lift2 ₓ (Ѧ α)(Ѧ α)]|>S.filter(ᵒ s)|>S.map(tuple2 s)) let ɷ=ɱ(fun s->M.find s ʋ|>S.collect(ᴓ s>>S.map(tuple2 s)))|>M.map(fun _->S.distinct>>S.toArray) let rec Ɣ i b d=M.find i b|>ᴓ d|>S.fold(đ i)(Some b) and đ i b d= let р b=S.map(S.filter(fun t->ᵒ d (M.find t b)))>>S.fold(fun b n->ᶺ(fun m->match S.toList n with|[]->None|h::[]->Ɣ h m d|_->b)b)(Some b) let ѵ u=match M.find i u with|[]->None|_::[]->S.fold(fun b n->ᶺ(M.find i>>S.head>>đ n b)b)(Some u)(M.find i ɷ)|_->Some u match b with|Some b when ᵒ d (M.find i b)->(M.updateWith(ᴓ d>>S.toList>>Some)i>>ѵ>>ᶺ (fun m -> M.find i ʋ|>р m))b|_->b let rec ŝ=ᶺ(fun m->match(M.toSeq>>S.sortBy(snd>>S.length)>>S.tryFind(snd>>S.length>>(<)1))m with Some(k,v)->S.map(Ɣ k m)v|>S.tryPick ŝ|_->Some m) let ř=S.zip Ͳ>>S.fold(fun b (k,v)->match b with Some m when ᵒ v α->Ɣ k m v|_->b)(S.map(flip tuple2 α)Ͳ|>M.ofSeq|>Some) let cm s p=Ѧ>>S.map p>>String.concat s let ƭ=ᶺ(M.values>>S.concat>>S.map string>>cm"\n\n"(cm"\n"(cm" "(String.concat"")))>>Some)>>Option.getOrElse"" File.ReadAllLines"top95.txt"|>S.map(ř>>ŝ>>ƭ)|>S.iter(printfn"%A")
Code deliberately messy just to play with definitions, as well as F# features and limitations.
WebBrowser Navigating event doesn't like async
async void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e) { // e.Cancel = true; // This is honored await SlowMethodAsync(); e.Cancel = true; // This is not }
Go figure…
Pipelining operations
Workaround for function pipelining in C#:
static U Pipe<T, U>(this T value, Func<T, U> predicate) => predicate(value); static void Pipe<T>(this T value, Action<T> predicate) => predicate(value);

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Combining collections
static IEnumerable<V> Combine<T, U, V>(this IEnumerable<T> first, IEnumerable<U> second, Func<T, U, V> resultSelector) => // first.SelectMany(a => second.Select(b => resultSelector(a, b))); // first.Join(second, _ => true, _ => true, resultSelector); from a in first from b in second select resultSelector(a, b);
For some reason I prefer the commented version.
Constructing disposable resources safely
Code analysis can be a pain for unnecessary reasons sometimes, specially CA2000, so trying to work around the case where the constructor can throw:
T SafeBuildDisposableResource<T>() where T : class, IDisposable, new() { T resource = null; try { resource = new T(); return resource; } catch { if (resource != null) { resource.Dispose(); } throw; } }
And a test:
DataTable GetDataTable() { var resource = SafeBuildDisposableResource<DataTable>(); // Add columns... // Add rows... return resource; }
Meh, but VS 2012 is happy now...
SynchronizationContext gotcha for Windows Forms
partial class MainForm : Form { private Progress<ViewProgress> progress = new Progress<ViewProgress>(ProgressHandler); ...
Big no no, there will be no SynchronizationContext at the time of construction and thus the handler will run on the thread pool rather than the UI thread. Construct on MainForm() instead. MSDN documentation remarks ftw once again.
Singleton
Still inspired by F#, moving Seq.singleton to C#:
static IEnumerable<T> ToSingleton<T>(this T source) { yield return source; }
Some F#
Playing with F# and all the functional awesomeness has been a bless, specially when coming from a Haskell background. And even for the simpler things, avoiding an intermediate state proves itself useful yet again. That C#:
var data = ReadData(dataFile); var resultA = calculateA(data); var resultB = calculateB(data); return Tuple.Create(resultA, resultB);
Becomes:
dataFile |> ReadData |> (fun data -> calculateA data, calculateB data)
Regardless of state, all I need is moving from an input to my results.

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Set Windows Forms control font size
Since Font.Size is read-only. Throws when value is less than or equal to zero:
static void SetFontSize(this Control target, float value) => target.Font = new Font(target.Font.Name, value, target.Font.Style, target.Font.Unit);
Expected<T> in C#
Based on Andrei Alexandrescu's Expected<T> for C++, the idea is sort of a Nullable<T> which carries over the failure data:
public class Expected<T> { private T ham; private Exception spam; private Expected() { } // nothing else to do public Expected(T value) { ham = value; HasValue = true; } public Expected(Expected<T> copy) { if (HasValue = copy.HasValue) { ham = copy.ham; } else { spam = copy.spam; } } public bool HasValue { get; private set; } public T Value { get { if (!HasValue) { throw spam; } return ham; } } public static Expected<T> FromException(Exception exception) => new Expected<T> { HasValue = false, spam = exception }; public static Expected<T> FromCode(Func<T> predicate) { try { return predicate(); } catch (Exception e) { return FromException(e); } } public static explicit operator T(Expected<T> value) => value.Value; public static implicit operator Expected<T>(T value) => new Expected<T>(value); public T GetValueOrDefault(T defaultValue = default(T)) => HasValue ? ham : defaultValue; public bool HasException<U>() => spam is U; public override string ToString() => HasValue ? ham.ToString() : spam.ToString(); }
And some tests:
Expected<int> ParseInt(string source) { try { return int.Parse(source); } catch (Exception e) { return Expected<int>.FromException(e); } } ... var test1 = ParseInt("123"); var test2 = ParseInt(null); var test3 = ParseInt("abc"); var test4 = Expected<int>.FromCode(() => int.Parse("123")); var test5 = Expected<int>.FromCode(() => int.Parse("abc")); var test6 = new Expected<int>(test2); Debug.Assert(test1.HasValue && test1.Value == 123); Debug.Assert(test2.HasValue == false); Debug.Assert(test2.HasException<ArgumentNullException>()); Debug.Assert(test3.HasException<ArgumentNullException>() == false); Debug.Assert(test1.HasException<ArgumentNullException>() == false); Debug.Assert(test3.HasException<Exception>()); Debug.Assert(test4.HasValue && test4.Value == 123); Debug.Assert(test5.GetValueOrDefault() == default(int)); Debug.Assert(test5.GetValueOrDefault(4) == 4); Debug.Assert(test6.HasException<ArgumentNullException>());
In my opinion, a lot nicer than TryParse()!