Skip to content

Instantly share code, notes, and snippets.

@chitoku-k
Created March 3, 2015 10:07
Show Gist options
  • Save chitoku-k/24a313babac0aa665546 to your computer and use it in GitHub Desktop.
Save chitoku-k/24a313babac0aa665546 to your computer and use it in GitHub Desktop.
LINQ 微妙に拡張シリーズ
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