我有一个循环运行检索实时股价。我想要做的是检查检索到的任何价格是否与我已经存储在字典中的价格不同,并通知我所有已更改的价格的详细信息。正在查看使用 INotifyCollectionChanged 的字典。
例如
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
namespace BasicExamples
{
class CollectionNotify:INotifyCollectionChanged
{
public Dictionary<string, string> NotifyDictionary{ get; set; }
public CollectionNotify()
{
NotifyDictionary = new Dictionary<string, string>();
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
CollectionChanged(this, e);
}
}
public void Add(object k, object v)
{
NotifyDictionary.Add(k.ToString(),v.ToString());
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,0));
}
public void Update(object k, object v)
{
bool isUpdated = false;
IList<string> changedItems = new List<string>();
int index;
if (NotifyDictionary.ContainsKey(k.ToString()))
{
NotifyDictionary[k.ToString()] = v.ToString();
changedItems.Add(k+":"+v);
isUpdated = true;
}
else
{
Add(k, v);
}
if (isUpdated)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace,changedItems,changedItems));
}
}
}
}
主程序调用 Add/Update 作为测试。但是,当循环通过 NotifyCollectionChangedEventArgs 时,我必须嵌套循环并强制转换为 IEnumerable - 这似乎是一个非常冗长的方法。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BasicExamples
{
class Program
{
//delegate
static void Main(string[] args)
{
//notify collection
CollectionNotify notify = new CollectionNotify();
notify.CollectionChanged += CollectionHasChanged;
notify.Add("Test1", "Test2");
notify.Add("Test2","Test2");
notify.Add("Test3", "Test3");
notify.Update("Test2", "Test1");
notify.Update("Test2", "Test3");
notify.Update("Test3", "Test1");
notify.Update("Test1", "Test3");
#region Lamba
//lamba
List<int> myList = new List<int>() {1,1,2,3,4,5,6};
List<int> newList = myList.FindAll(s =>
{
if (s == 1)
{
return true;
}
return false;
});
foreach (int b in newList)
{
Console.WriteLine(b.ToString());
}
#endregion
}
public static void CollectionHasChanged(object sender, EventArgs e)
{
NotifyCollectionChangedEventArgs args = (NotifyCollectionChangedEventArgs) e;
if (args.Action == NotifyCollectionChangedAction.Replace)
{
foreach (var item in args.NewItems)
{
foreach (var nextItem in (IEnumerable)item)
{
Console.WriteLine(nextItem);
}
}
}
}
}
}
我想我的问题有两个方面:- A:这是使用应通报字典的最佳方式吗?B:我应该使用上面的嵌套循环来检索更新的值吗?
提前致谢