如何检测List <string>是否已更改?什么是最后添加的项目?</string>

时间:2014-07-24 04:16:09

标签: c# .net

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

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();            
    }
    
  3. 我想仅在索引0中存在一个单词/字符串时才启动timer3

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

    仅在50秒或更晚之后,列表发生了变化,并且其中一个单词/字符串再次存在于索引0中,然后再次启动计时器3.

2 个答案:

答案 0 :(得分:11)

通用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
        }
}

答案 1 :(得分:-1)

要检测您的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]; //已添加的列表中的最后一项