日期:2014-05-17  浏览次数:20464 次

如何用LINQ查找两个list数据实体中不同的记录
有一个数据实体类
public class wage
{
  public int id{set;get;}
  public string card{set;get;}
  public string name{set;get;}
  public decimal price{set;get;}
}

现在有两个不同的list集合,数据是分别是从txt和excel中获取的
List<wage> list1 = new List(wage)();
List<wage> list2 = new List(wage)();


如何找出这两个集合中不同的记录?条件是card,name,price都相同,否则为不同,谢谢

------解决方案--------------------
C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class wage
    {
        public int id { set; get; }
        public string card { set; get; }
        public string name { set; get; }
        public decimal price { set; get; }
    }

    class MyComparer : IEqualityComparer<wage>
    {
        public bool Equals(wage x, wage y)
        {
            return x.card == y.card && x.name == y.name && x.price == y.price;
        }

        public int GetHashCode(wage obj)
        {
            return obj.card.GetHashCode() ^ obj.name.GetHashCode() ^ obj.price.GetHashCode();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            List<wage> list1 = new List<wage>() 
            {
                new wage() { id = 1, card = "card1", name = "name1", price = 1 },
                new wage() { id = 2, card = "card2", name = "name2", price = 2 },
                new wage() { id = 3, card = "card3", name = "name3", price = 3 },
                new wage() { id = 5, card = "card5", name = "name5", price = 5 },
                new wage() { id = 6, card = "card8", name = "name8", price = 8 }
            };
            List<wage> list2 = new List<wage>() 
            {
                new wage() { id = 1, card = "card1", name = "name1", price = 2 },
                new wage() { id = 2, card = "card2", name = "name2", price = 2 },
                new wage() { id = 3, card = "card3", name = "name4", price = 3 },
                new wage() { id = 4, card = "card4", name = "name4", price = 4 },
                new wage() { id = 5, card = "card8", name = "name8", price = 8 }
            };
            var result = list1.Union(list2, new MyComparer()).Except(list1.Intersect(list2, new MyComparer()), new MyComparer());
            foreach (var item in result)
            {
                Console.WriteLine("id = {0}, card = {1}, name = {2}, price = {3}", item.id, item.card, item.name, item.price);
            }
        }
    }
}