如何对字符串使用 .Take() 并在末尾获取字符串?

发布于 2024-11-08 13:09:53 字数 531 浏览 9 评论 0原文

LINQ to Objects 支持对字符串对象的查询,但是当我使用如下所示的代码时:

string SomeText = "this is some text in a string";
return SomeText.Take(6).ToString();

我得到的只是:

System.Linq.Enumerable+<TakeIterator>d__3a`1[System.Char]

这在 这个问题 但这是我实际上想做的事情,但我无法通过任何地方的搜索找到它。

我知道还有其他方法来操作字符串,但我也知道您可以使用 LINQ 做一些非常酷的技巧,我只是想知道是否有一种方法可以使用 LINQ 将字符串修剪到一定长度?

LINQ to Objects supports queries on string objects but when I use code such as below:

string SomeText = "this is some text in a string";
return SomeText.Take(6).ToString();

All I get is:

System.Linq.Enumerable+<TakeIterator>d__3a`1[System.Char]

This is discussed as an "accident" in this question but this is what I am actually trying to do and I cannot find it through search anywhere.

I know there are other ways to manipulate strings but then I also know you can do some really cool tricks with LINQ and I just would like to know if there is a way to trim a string to a certain length with LINQ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

记忆消瘦 2024-11-15 13:09:53

System.Linq 中没有内置方法来执行此操作,但您可以相当轻松地编写自己的扩展方法:

public static class StringExtensions
{
    public static string ToSystemString(this IEnumerable<char> source)
    {
        return new string(source.ToArray());
    }
}

不幸的是,因为 object.ToString 存在于所有 .NET 对象上,所以您必须给出方法使用不同的名称,以便编译器将调用您的扩展方法,而不是内置的 ToString

根据您下面的评论,最好质疑这是否是正确的方法。因为 String 通过其公共方法公开了很多功能,所以我会将此方法实现为 String 本身的扩展:

/// <summary>
/// Truncates a string to a maximum length.
/// </summary>
/// <param name="value">The string to truncate.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>The input string, truncated to <paramref name="length"/> characters.</returns>
public static string Truncate(this string value, int length)
{
    if (value == null)
        throw new ArgumentNullException("value");
    return value.Length <= length ? value : value.Substring(0, length);
}

您可以按如下方式使用它:

string SomeText = "this is some text in a string";
return SomeText.Truncate(6);

这具有以下优点 :当字符串已经短于所需长度时,不创建任何临时数组/对象。

There's no method built in to System.Linq to do this, but you could write your own extension method fairly easily:

public static class StringExtensions
{
    public static string ToSystemString(this IEnumerable<char> source)
    {
        return new string(source.ToArray());
    }
}

Unfortunately, because object.ToString exists on all .NET objects, you would have to give the method a different name so that the compiler will invoke your extension method, not the built-in ToString.

As per your comment below, it's good to question whether this is the right approach. Because String exposes a lot of functionality through its public methods, I would implement this method as an extension on String itself:

/// <summary>
/// Truncates a string to a maximum length.
/// </summary>
/// <param name="value">The string to truncate.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <returns>The input string, truncated to <paramref name="length"/> characters.</returns>
public static string Truncate(this string value, int length)
{
    if (value == null)
        throw new ArgumentNullException("value");
    return value.Length <= length ? value : value.Substring(0, length);
}

You would use it as follows:

string SomeText = "this is some text in a string";
return SomeText.Truncate(6);

This has the advantage of not creating any temporary arrays/objects when the string is already shorter than the desired length.

北恋 2024-11-15 13:09:53

只需创建 string

string res = new string(SomeText.Take(6).ToArray());

还要注意 string 原生方法

string res = SomeText.Substring(0, 6);

Just create string

string res = new string(SomeText.Take(6).ToArray());

Also pay attention to string native methods

string res = SomeText.Substring(0, 6);
|煩躁 2024-11-15 13:09:53

我自己也遇到过几次这种情况,并使用以下方法:

string.Join(string.Empty,yourString.Take(5));

I've run into this myself a few times and use the following:

string.Join(string.Empty,yourString.Take(5));
诠释孤独 2024-11-15 13:09:53

SomeText.Take(6) 将返回 IEnumerable of char of char,而ToString方法不会返回可疑的字符串,您需要像下面这样调用它:

string [] array = SomeText.Take(6).ToArray();
string result = new string(array);

SomeText.Take(6) will returns an IEnumerable of char of char, and ToString method will not return the suspected string you need to call it like the following:

string [] array = SomeText.Take(6).ToArray();
string result = new string(array);
独自←快乐 2024-11-15 13:09:53

我在查找 LINQ 和 string 时发现了这个问题。

您可以在返回数据类型时使用 IEnumerable 而不是 string
您还可以在 如何查询字符串中的字符 (LINQ) (C#)

这是解决方案。

public class Program
{
    public static void Main()
    {
        foreach (var c in LinqString())
        {
            Console.WriteLine(c);
        }
        //OR
        Console.WriteLine(LinqString().ToArray());
    }

    private static IEnumerable<char> LinqString()
    {
        //This is Okay too...
        //IEnumerable<char> SomeText = "this is some text in a string";

        string SomeText = "this is some text in a string";
        
        return SomeText.Skip(4).Take(6);
    }
}

I found this question when I was looking up about LINQ and string.

You can use IEnumerable<char> instead of string in returning data type.
You can also learn more about it at How to query for characters in a string (LINQ) (C#)

And here is the solution.

public class Program
{
    public static void Main()
    {
        foreach (var c in LinqString())
        {
            Console.WriteLine(c);
        }
        //OR
        Console.WriteLine(LinqString().ToArray());
    }

    private static IEnumerable<char> LinqString()
    {
        //This is Okay too...
        //IEnumerable<char> SomeText = "this is some text in a string";

        string SomeText = "this is some text in a string";
        
        return SomeText.Skip(4).Take(6);
    }
}
迎风吟唱 2024-11-15 13:09:53

使用 C# 8 及更高版本...

抓取最后 6 位数字(如果输入少于 8 个字符,则失败

string SomeText = "this is some text in a string";
string result =  SomeText[^6..];

一个受保护的版本,将处理少于 6 个字符的字符串。 ..

string SomeText = "this is some text in a string";
string result = SomeText[^(Math.Min(6, SomeText.Length))..];

with C# 8 and later...

grab the last 6 digits (fails if the input is less than 8 chars)

string SomeText = "this is some text in a string";
string result =  SomeText[^6..];

a protected version that will handle strings less then 6 chars...

string SomeText = "this is some text in a string";
string result = SomeText[^(Math.Min(6, SomeText.Length))..];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文