簡體   English   中英

我有一個項目列表,並將其復制到集合中。 如果列表發生任何變化,它將自動反映在集合中

[英]I have a list of items and have copied it to a collection. If any changes happen to the list it should automatically reflect in the collection

我的專案是

步驟1:創建一個C#控制台應用程序,該應用程序應該創建一個String類型的列表,並添加item1,item 2和item 3。

步驟2:創建一個String類型的Collection並復制這些項目。

步驟3:如果List對象發生任何更改,它應該反映在Collection對象中。

我成功完成了直到步驟2,我的代碼是

class Program
    {
        static void Main(string[] args)
        {
            List<string> newList = new List<string>();
            newList.Add("Item 1");
            newList.Add("Item 2");
            newList.Add("Item 3");

            Collection<string> newColl = new Collection<string>();

            foreach (string item in newList)
            {
                newColl.Add(item);
            }

            Console.WriteLine("The items in the collection are");
            foreach (string item in newColl)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }

現在,如果列表中發生更改,它也將如何反映在collections對象中?

嘗試使用ObservableCollection而不是List<string>並訂閱事件CollectionChanged 這只是一個天真的實現,只是為了給出總體思路。 您應該添加參數檢查或執行其他類型的同步,因為您沒有說過應該如何在Collection上准確反映更改。

ObservableCollection<string> newList = new ObservableCollection<string>();
newList.Add("Item 1");
newList.Add("Item 2");
newList.Add("Item 3");

Collection<string> newColl = new Collection<string>();


newList.CollectionChanged += (sender, args) => 
        {
            foreach (var newItem in args.NewItems)
            {
                newColl.Add(newItem);
            }
            foreach (var removedItem in args.OldItems)
            {
                newColl.Remove(removedItem);
            }
        };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM