ライブ株価を取得するループを実行しています。私がやりたいことは、取得した価格のいずれかが既に辞書に保存されている価格と異なるかどうかを確認し、変更されたすべての価格の詳細を通知することです。INotifyCollectionChanged を利用して Dictionary の行に沿って探していました。
例えば
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);
}
}
}
}
}
}
私の質問は 2 つあると思います:- A: これは、通知可能な辞書を使用する最良の方法ですか? B: 更新された値を取得するには、上記のようにネストされたループを使用する必要がありますか?
前もって感謝します