簡體   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