繁体   English   中英

如何检测List <string> 被改变了 ? 最后添加的项目是什么?

[英]How can i detect if List<string> was changed ? And what is the last item that was added?

我有一个计时器刻度事件:

private void timer2_Tick(object sender, EventArgs e)
{
    combindedString = string.Join(Environment.NewLine, ListsExtractions.myList);
    richTextBox1.SelectAll();
    richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
    richTextBox1.Text = combindedString;
}

计时器设置为50000,时间一直在反复运行。 现在,当我运行我的程序时, List<string> myList有3个项目:

Index 0: Hello world
Index 1: 24/7/2014 21:00
Index 2: http://test.com

50秒后有两个选项:列表未更改或更改/更长。 如果没有改变什么都不做,但如果改变了最新添加的项目。 例如,如果列表现在已更改为此...

Index 0: This is the latest item added in index 0
Index 1: 24/7/2014 22:00
Index 2: http://www.google.com
Index 3: ""
Index 4: Hello world
Index 5: 24/7/2014 21:00
Index 6: http://test.com

...然后我需要做另外两个动作:

  1. 第一次运行程序时,检查最近的项目(本例中Index 0处的字符串)是否包含两个单词/字符串。 如果是,那么做一些事情,否则什么都不做。
    但是,如果它确实包含单词/字符串并且我们“做某事”,则只在50秒后执行一次; 即使单词/字符串在索引0中再次存在,也不要再次执行此操作。

  2. 50秒后,如果列表发生变化,并且在Index 0存在这样的单词/字符串,则在50秒后再做一次。 如果列表没有更改,即使索引0中仍然存在单词/字符串,也不要再次执行此操作。

     if (rlines[0].Contains("צבע אדום") || rlines[0].Contains("אזעקה")) { timer3.Start(); } 

我想只在索引0中存在一个单词/字符串时才启动timer3

如果50秒后没有任何变化,请不要再次启动timer3

只有在50秒或更晚之后,列表才会更改并且其中一个单词/字符串再次存在于索引0中,然后再次启动计时器3。

通用List<T>类不支持列表更改的通知。
您正在寻找的是ObservableCollection<T>
它有一个CollectionChanged ,在修改集合时触发。

您可以通过以下方式使用它:

using System.Collections.ObjectModel;

ObservableCollection<string> myList;

//The cnstructor 
public MyClassname()
{
  this.myList = new ObservableCollection<string>();
  this.myList.CollectionChanged += myList_CollectionChanged;
}

void myList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
        //list changed - an item was added.
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            //Do what ever you want to do when an item is added here...
            //the new items are available in e.NewItems
        }
}

要检测list已更改,请使用以下方法检查列表项计数:必须包含包含当前列表项计数的temp变量:

int temp = list.Count;//获取List中包含的元素数。

然后当你添加项目时:

list.add("string one");

然后使用temp变量做这样的事情:

if(temp != list.Count){
Console.WriteLine("list was changed.");
}

那么当然如果您的列表没有排序:您可以获得最后一项:

list[list.Count - 1]; //添加的列表中的最后一项

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM