C# ObservableCollection(或List也適用)的差集

  • 2777
  • 0
  • 2016-01-07

摘要:C# ObservableCollection(或List也試用)的差集

其實原理就是A判斷B裡面有的A就拿掉,用到contain的概念。

 

假設你的list的原型長這樣


        public class iconItem
        {
            public string Name { get; set; }
            public string Img { get; set; }
        }

 

那麼你的Difference方法大概長這樣:
 


        private ObservableCollection<iconItem> Difference(ObservableCollection<iconItem> oc1, ObservableCollection<iconItem> oc2)
        {
            ObservableCollection<iconItem> differPoints = new ObservableCollection<iconItem>();
            foreach (var p in oc1)
            {
                bool isContain = false;
                for (int j = 0; j < oc2.Count; j++)
                {
                    if (p.Location == oc2[j].Name && p.Img == oc2[j].Img)
                        isContain = true;
                }
                if (isContain == true)
                    continue;
                differPoints.Add(p);
            }
            return differPoints;
        }

 

如果是用List當然就是:


         private List<iconItem> Difference(List<iconItem> list1,List<iconItem> list2)
        {
           List<iconItem> differPoints = new List<iconItem>();
            foreach (var p in list1)
            {
                bool isContain = false;
                for (int j = 0; j < list2.Count; j++)
                {
                    if (p.Location == list2[j].Name && p.Img == list2[j].Img)
                        isContain = true;
                }
                if (isContain == true)
                    continue;
                differPoints.Add(p);
            }
            return differPoints;
        }

 

要是用聯集就很簡單,因為List和 ObservableCollection本身就有聯集的方法了~叫做Union()。


Edit:

 

要是交集的話,就是大家都有,
那就比較簡單了:

 


        private List<iconItem> Intersaction(List<iconItem> list1,List<iconItem> list2)
        {
           List<iconItem> differPoints = new List<iconItem>();
            foreach (var p in list1)
            {
                for (int j = 0; j < list2.Count; j++)
                {
                    if (p.Location == list2[j].Name && p.Img == list2[j].Img)
                        differPoints.Add(p);
                }
            }
            return differPoints;
        }

 

順序上我的習慣是將最後的結果當作A(第一個參數),被比較的當作B(第二個參數),
如果習慣不同的可能就要把參數相反囉!