星期五, 4月 28, 2017

[LINQ] Except

使用 LINQ Except 時發現到,為什麼都沒有作用,後來查 MSDN 才晃然大悟,自訂的 class 要指定 IEqualityComparer,Except 才知道要怎麼進行資料篩選,寫個簡易範例紀錄
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var demoData1 = new List<Employ>()
            {
                new Employ() { EmpNO = "0001" , EmpName = "張三"},
                new Employ() { EmpNO = "0002" , EmpName = "李四"},
                new Employ() { EmpNO = "0003" , EmpName = "王五"}
            };

            var demoData2 = new List<Employ>()
            {
                new Employ() { EmpNO = "0001" , EmpName = "張三"},
            };

            Console.WriteLine("沒有指定 IEqualityComparer 結果");
            var result1 = demoData1.Except(demoData2);
            ShowData(result1);

            Console.WriteLine("指定 IEqualityComparer 結果");
            var result2 = demoData1.Except(demoData2,new EmployComparer());
            ShowData(result2);
        }

        private static void ShowData( IEnumerable<Employ> datas)
        {
            foreach (var e in datas)
            {
                Console.WriteLine($"           {e.EmpNO}-{e.EmpName}");
            }
        }
    }

    class Employ
    {
        public string EmpNO { get; set; }
        public string EmpName { get; set; }
    }

    class EmployComparer : IEqualityComparer<Employ>
    {
        public bool Equals(Employ x, Employ y)
        {
            //Check whether the compared objects reference the same data.
            if (Object.ReferenceEquals(x, y)) return true;

            //Check whether any of the compared objects is null.
            if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
                return false;

            //Check whether the Employ' properties are equal.
            return x.EmpNO == y.EmpNO && x.EmpName == y.EmpName;
        }

        public int GetHashCode(Employ e)
        {
            //Check whether the object is null
            if (Object.ReferenceEquals(e, null)) return 0;

            //Get hash code for the EmpNO field.
            int hashEmpNO = e.EmpNO == null ? 0 : e.EmpNO.GetHashCode();

            //Get hash code for the EmpName field.
            int hashEmpName = e.EmpName == null ?  0 : e.EmpName.GetHashCode();

            //Calculate the hash code for the Employ.
            return hashEmpNO ^ hashEmpName;
        }
    }
}
[LINQ] Except

沒有留言:

張貼留言