从textBox中删除行。

时间:2016-04-29 09:01:50

标签: c# winforms serial-port

我正在从serialport读取数据。我只想在文本框中显示40行。

如何删除旧线条以便为新线条添加位置?

我尝试了以下代码:

     int numOfLines = 40; 
    var lines = this.textBox1.Lines;
    var newLines = lines.Skip(numOfLines);
    this.textBox1.Lines = newLines.ToArray();

但它给了我错误,说" '串[]'不包含' Skip'的定义没有扩展方法' Skip'接受类型' string []'的第一个参数可以找到"。

3 个答案:

答案 0 :(得分:0)

我认为您忘记添加using System.Linq;指令

P.S。如果您希望显示最后40行,则可以使用此问题中描述的方法:Using Linq to get the last N elements of a collection?

答案 1 :(得分:0)

您需要添加对Linq的引用:

using System.Linq;

答案 2 :(得分:0)

Skip是LINQ的扩展方法。您必须在项目中添加对System.Core的引用,如果需要using System.Linq;指令

修改

由于您似乎“无法”使用LINQ,这里是一个非LINQ解决方案(就像重新发明轮子的实验一样):

扩展方法

public static class ExtMeth
{
    public static IEnumerable<string> SkipLines(this string[] s, int number)
    {
        for (int i = number; i < s.Length; i++)
        {
            yield return s[i];
        }
    }

    public static string[] ToArray(this IEnumerable<string> source)
    {
        int count = 0;
        string[] items = null;
        foreach (string it in source)
        {
            count++;
        }
        int index = 0;
        foreach (string item in source)
        {
            if (items == null)
            {
                items = new string[count];
            }
            items[index] = item;
            index++;
        }
        if (count == 0) return new string[0];
        return items;
    }
}

用法

this.textBox1.Lines = this.textBox1.Lines.SkipLines(2).ToArray();
相关问题