欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#中使用Lambda表達式自定義比較器實現(xiàn)兩個列表合并實例

 更新時間:2014年10月25日 10:59:39   投稿:junjie  
這篇文章主要介紹了C#中使用Lambda表達式自定義比較器實現(xiàn)兩個列表的合并實例,本文給出示例代碼和運行效果,需要的朋友可以參考下

一次項目有這樣的需求,本地存儲了json數(shù)據(jù),可以轉化為對應的List列表,現(xiàn)在需要更新,從服務器那里獲取最新的數(shù)據(jù)更改??偟膩碚f就是本地有個List表,如果數(shù)據(jù)需要更新,則會向服務器發(fā)送請求來獲取需要更改的部分List表格,然后客戶端這邊就要去處理合并完整這次的更新,弄了一個下午,終于搞定,這次來mark一下。

主要推送的數(shù)據(jù)的兩個特性:

1.如果之前的列表需要增加,則出現(xiàn)在最新的數(shù)據(jù)推送List中

2.如果數(shù)據(jù)需要修改的話,則一樣推送更新,保持id不變,內容有所改變

示例代碼如下圖:

復制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace test
{
    public class date
    {
        public int id { set; get; }
        public string color { set; get; }
        public string name { set; get; }
        public decimal price { set; get; }

        public string time { get; set; }
    }

    class MyComparer : IEqualityComparer<date>
    {
        public bool Equals(date x, date y)
        {
            return x.id == y.id;
        }

        public int GetHashCode(date obj)
        {
            return obj.id.GetHashCode();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<date> list1 = new List<date>()
            {
                new date() { id = 1, color = "1", name = "name1", price = 1,time="時間" },
                new date() { id = 2, color = "2", name = "name2", price = 2,time="時間" },
                new date() { id = 3, color = "3", name = "name3", price = 3,time="時間" },
                new date() { id = 5, color = "5", name = "name5", price = 5,time="時間" },
                new date() { id = 6, color = "6", name = "name8", price = 8,time="時間" }
            };
            List<date> list2 = new List<date>()
            {
                new date() { id = 1, color = "修改", name = "修改", price = 2,time="時間" },
                new date() { id = 8, color = "增加", name = "增加", price = 2,time="時間" }
            };
            var result = list2.Union(list1, new MyComparer());
            foreach (var item in result)
            {
                Console.WriteLine("id = {0}, card = {1}, name = {2}, price = {3}", item.id, item.color, item.name, item.price,item.time);
            }
        }
    }
}

測試的結果為:

從結果看出,id=1的數(shù)據(jù)需要修改,所以最新生成的List表中id為1的所有屬性都是更改后的結果,而在list1中沒有id為8的數(shù)據(jù),說明這個是需要新增進去的一條記錄,因此在最新的List也有了,這次主要用到自定義的比較器,去實現(xiàn)IEqualityComparer<>這個接口。另外還用到了Lambda表達式

var result = list2.Union(list1, new MyComparer());特別是Union這個方法的使用,該方法還有很多種用法,這里就舉個例子而已啦。

相關文章

最新評論