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

标签 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

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

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

  2. 如果 List 在 50 秒后发生变化并且在 Index 0 中这个单词/字符串存在,50 秒后只做一次。如果列表没有改变,即使单词/字符串仍然存在于索引 0 中,也不要再做一次。

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

我要开始timer3仅当其中一个单词/字符串存在于索引 0 中时。

如果 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
        }
}

关于c# - 我如何检测 List<string> 是否已更改?最后添加的项目是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24925037/

相关文章:

c# - 如何组合多个 GeometryGroup 对象?

c# - 如何以编程方式安全关闭 Google Chrome

c# - XDocument.Save() 在每个 XElement 上添加不需要的命名空间

c# - 为什么 C# 中的事件要带 (sender, EventArgs)?

c# - 如何在 asp.net 中恢复 session

c# - 在 C# 中将参数传递给正在运行的进程

c# - Azure Cosmos MongoDB - 使用分片键创建集合

c# - Objective C 前端 - Java/C# 后端

c# - 在循环中获取 Null 异常错误。尝试调试

c# - 我如何充分了解 CLR 以对性能问题做出有根据的猜测?