Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created November 25, 2016 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neuecc/6cbec456dab4d0bb3c81976799b5fc6e to your computer and use it in GitHub Desktop.
Save neuecc/6cbec456dab4d0bb3c81976799b5fc6e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
class Base { }
class A : Base { }
class B : Base { }
class Program
{
static void Main(string[] args)
{
var objects1 = new Base[] { new A(), new B() };
var objects2 = new int?[] { 1, 2, 100, null, 1000 };
var hoge = objects1.SelectMany(x => x as A);
var huga = objects2.SelectMany(x => x);
}
}
public static class FlatMapLikeExtensions
{
public static IEnumerable<U> SelectMany<T, U>(this IEnumerable<T> source, Func<T, U> selector)
where U : class
{
foreach (var item in source)
{
var v = selector(item);
if (v != null) yield return v;
}
}
public static IEnumerable<U> SelectMany<T, U>(this IEnumerable<T> source, Func<T, U?> selector)
where U : struct
{
foreach (var item in source)
{
var v = selector(item);
if (v.HasValue) yield return v.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment