C# - string[] 不包含“SkipLast”的定义并且没有可访问的扩展方法

Stp*_*111 3 c#

.NET 框架 4.7.2。Visual Studio 2019。有关此错误的其他帖子中没有具体解决此问题。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stuff
{
    class Program
    {
        static void Main(string[] args)
        {
         string firstPart = "ABC 123 XYZ";
         string firstPartMinusLast = string.Join(" ", firstPart.Split(' ').SkipLast(1));
         Console.WriteLine(firstPartMinusLast);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到一个 Intellisense 错误SkipLast

string[] 不包含“SkipLast”的定义,并且找不到接受“string[]”类型的第一个参数的可访问扩展方法“SkipLast”(您是否缺少 using 指令或程序集引用?)

根据我可以在网上找到的任何文档,using System.Linq应该涵盖这种方法吗?

Ruf*_*s L 7

Enumerable.SkipLast 如果您选中文档顶部的紫色框,您会发现它在 .NET Framework 4.7.2 中不可用


不管怎样,源代码在这里,所以你可以自己添加它。逻辑很精彩:

  • 第一次调用枚举器时,count会从队列中取出项目source并将其添加到队列中,然后将项目出队并返回。
  • 在后续调用中,下一个项目将添加到队列中,如果这不是 中的最后一个项目source,则项目将出队并返回。
  • 完成后,队列包含最后一个项目的缓存source(我们想跳过),并且它是在事先不知道source包含多少项目的情况下完成的。
public static class Extensions
{
    public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source, int count)
    {
        var queue = new Queue<T>();

        using (var e = source.GetEnumerator())
        {
            while (e.MoveNext())
            {
                if (queue.Count == count)
                {
                    do
                    {
                        yield return queue.Dequeue();
                        queue.Enqueue(e.Current);
                    } while (e.MoveNext());
                }
                else
                {
                    queue.Enqueue(e.Current);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)