首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >你最喜欢的没有内置的LINQ to Objects操作符是什么?

你最喜欢的没有内置的LINQ to Objects操作符是什么?
EN

Stack Overflow用户
提问于 2010-09-05 17:49:20
回答 33查看 6.1K关注 0票数 71

使用扩展方法,我们可以编写方便的LINQ运算符来解决一般问题。

我想知道您在System.Linq名称空间中缺少哪些方法或重载,以及您是如何实现它们的。

最好使用干净和优雅的实现,也许可以使用现有的方法。

EN

回答 33

Stack Overflow用户

回答已采纳

发布于 2010-09-05 18:18:24

附加和准备

(自编写此答案以来,这些内容已添加到.NET中。)

/// <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;
}
票数 31
EN

Stack Overflow用户

发布于 2010-09-05 17:52:46

每一个

对于纯粹主义者来说什么都不是,但是它非常有用!

 public static void Each<T>(this IEnumerable<T> items, Action<T> action)
 {
   foreach (var i in items)
      action(i);
 }
票数 16
EN

Stack Overflow用户

发布于 2010-09-05 18:23:22

ToQueue和ToStack

/// <summary>Creates a <see cref="Queue&lt;T&gt;"/> from an enumerable
/// collection.</summary>
public static Queue<T> ToQueue<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");
    return new Queue<T>(source);
}

/// <summary>Creates a <see cref="Stack&lt;T&gt;"/> from an enumerable
/// collection.</summary>
public static Stack<T> ToStack<T>(this IEnumerable<T> source)
{
    if (source == null)
        throw new ArgumentNullException("source");
    return new Stack<T>(source);
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3645644

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档