近期收集一些基於IEnumerable<T>擴展方法,它給我們帶了很多便利,有時的確是實用的。其中有Alternate,Append,Prepend,Distinct,Contains。具體怎麼用呢,看下面的UnitTest.
Code:
/// <summary>
/// IEnumerableExtension
/// </summary>
public static class IEnumerableExtensions
{
#region Methods (5)
// Public Methods (5)
/// <summary>
/// Alternates the specified first.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <param name="first">The first.</param>
/// <param name="second">The second.</param>
/// <returns></returns>
public static IEnumerable<TSource> Alternate<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
{
using (IEnumerator<TSource> e1 = first.GetEnumerator())
using (IEnumerator<TSource> e2 = second.GetEnumerator())
while (e1.MoveNext() && e2.MoveNext())
{
yield return e1.Current;
yield return e2.Current;
}
}
/// <summary>
/// Appends the specified source.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <param name="source">The source.</param>
/// <param name="element">The element.</param>
/// <returns>IEnumerable<TSource></returns>
public static IEnumerable<TSource> Append<TSource>(this IEnumerable<TSource> source, TSource element)
{
using (IEnumerator<TSource> e1 = source.GetEnumerator())
while (e1.MoveNext())
yield return e1.Current;
yield return element;
}
/// <summary>
/// Determines whether [contains] [the specified source].
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="source">The source.</param>
/// <param name="value">The value.</param>
/// <param name="selector">The selector.</param>
/// <returns>
/// <c>true</c> if [contains] [the specified source]; otherwise, <c>false</c>.
/// </returns>
public static bool Contains<TSource, TResult>(
this IEnumerable<TSource> source, TResult value, Func<TSource, TResult> selector)
{
foreach (TSource sourceItem in source)
{
TResult sourceValue = selector(sourceItem);
if (sourceValue.Equals(value))
return true;
}
return false;
}
/// <summary>
/// Distincts the specified source.
/// </summary>
/// <typeparam name="TSource">The type of the source.</typeparam>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="source">The source.</param>
/// <param name="comparer">The comparer.</param>
/// <returns>IEnumerable<TSource></returns>
public static IEnumerable<TSource> Distinct<TSource, TResult>(
this IEnumerable<TSource> source, Func<TSource, TResult> comparer)
{
return source.Distinct(new DynamicComparer<TSource, TResult>(comparer));
}
/// <summary>
/// Prepends the specified source.
/// </summary>
&nb