如何在字符串上执行".Take()"并在末尾获得一个字符串? [英] how to `.Take()` on a string and get a string at the end?

查看:109
本文介绍了如何在字符串上执行".Take()"并在末尾获得一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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();

我得到的是:

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.

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

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?

推荐答案

System.Linq中没有内置方法可以做到这一点,但是您可以相当轻松地编写自己的扩展方法:

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());
    }
}

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

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.

根据您在下面的评论,很好地质疑这是否是正确的方法.由于String通过其公共方法公开了许多功能,因此我将将此方法实现为String本身的扩展:

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.

这篇关于如何在字符串上执行".Take()"并在末尾获得一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆