What's your favorite LINQ to Objects operator which is not built
With extension methods, we can write handy LINQ operators which solve generic problems.
I want to hear which methods or overloads you are missing in the System.Linq
namespace and how you implemented them.
Clean and elegant implementations, maybe using existing methods, are preferred.
追加和前置
/// <summary>Adds a single element to the end of an IEnumerable.</summary>
/// <typeparam name="T">Type of enumerable to return.</typeparam>
/// <returns>IEnumerable containing all the input elements, followed by the
/// specified additional element.</returns>
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T element)
{
if (source == null)
throw new ArgumentNullException("source");
return concatIterator(element, source, false);
}
/// <summary>Adds a single element to the start of an IEnumerable.</summary>
/// <typeparam name="T">Type of enumerable to return.</typeparam>
/// <returns>IEnumerable containing the specified additional element, followed by
/// all the input elements.</returns>
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> tail, T head)
{
if (tail == null)
throw new ArgumentNullException("tail");
return concatIterator(head, tail, true);
}
private static IEnumerable<T> concatIterator<T>(T extraElement,
IEnumerable<T> source, bool insertAtStart)
{
if (insertAtStart)
yield return extraElement;
foreach (var e in source)
yield return e;
if (!insertAtStart)
yield return extraElement;
}
I'm surprised no one has mentioned the MoreLINQ project yet. It was started by Jon Skeet and has gained some developers along the way. From the project's page:
LINQ to Objects is missing a few desirable features.
This project will enhance LINQ to Objects with extra methods, in a manner which keeps to the spirit of LINQ.
Take a look at the Operators Overview wiki page for a list of implemented operators.
It is certainly a good way to learn from some clean and elegant source code.
Each
Nothing for the purists, but darn it's useful!
public static void Each<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (var i in items)
action(i);
}
链接地址: http://www.djcxy.com/p/42818.html
上一篇: 如何发送电子邮件附件?