compare two list and return not matching items using linq

后端 未结 10 572
死守一世寂寞
死守一世寂寞 2021-02-01 02:52

i have a two list

List SentList;
List MsgList;

both have the same property called MsgID;

MsgList            


        
10条回答
  •  野性不改
    2021-02-01 03:11

    As an extension method

    public static IEnumerable AreNotEqual(this IEnumerable source, Func sourceKeySelector, IEnumerable target, Func targetKeySelector) 
    {
        var targetValues = new HashSet(target.Select(targetKeySelector));
    
        return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
    }
    

    eg.

    public class Customer
    {
        public int CustomerId { get; set; }
    }
    
    public class OtherCustomer
    {
        public int Id { get; set; }
    }
    
    
    var customers = new List()
    {
        new Customer() { CustomerId = 1 },
        new Customer() { CustomerId = 2 }
    };
    
    var others = new List()
    {
        new OtherCustomer() { Id = 2 },
        new OtherCustomer() { Id = 3 }
    };
    
    var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();
    
    Debug.Assert(result.Count == 1);
    Debug.Assert(result[0].CustomerId == 1);
    

提交回复
热议问题