Created
March 3, 2015 10:07
-
-
Save chitoku-k/24a313babac0aa665546 to your computer and use it in GitHub Desktop.
LINQ 微妙に拡張シリーズ
This file contains hidden or 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; | |
using System.Linq; | |
public static class EnumerableExtensions | |
{ | |
private static int IndexOfByForEach<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) | |
{ | |
int index = 0; | |
foreach (var item in source) | |
{ | |
if (predicate(item)) | |
{ | |
return index; | |
} | |
index++; | |
} | |
return -1; | |
} | |
public static int IndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) | |
{ | |
var list = source as List<TSource>; | |
if (list != null) | |
{ | |
return list.FindIndex(x => predicate(x)); | |
} | |
var array = source as TSource[]; | |
if (array != null) | |
{ | |
return Array.FindIndex(array, x => predicate(x)); | |
} | |
return source.IndexOfByForEach(predicate); | |
} | |
public static int LastIndexOf<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) | |
{ | |
var list = source as List<TSource>; | |
if (list != null) | |
{ | |
return list.FindLastIndex(x => predicate(x)); | |
} | |
var array = source as TSource[]; | |
if (array != null) | |
{ | |
return Array.FindLastIndex(array, x => predicate(x)); | |
} | |
return source.Reverse().IndexOfByForEach(predicate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment