Created
November 25, 2016 12:22
-
-
Save neuecc/6cbec456dab4d0bb3c81976799b5fc6e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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