compare two list and return not matching items using linq

后端 未结 10 545
死守一世寂寞
死守一世寂寞 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:08
    List<Car> cars = new List<Car>() {  new Car() { Name = "Ford", Year = 1892, Website = "www.ford.us" }, 
                                        new Car() { Name = "Jaguar", Year = 1892, Website = "www.jaguar.co.uk" }, 
                                        new Car() { Name = "Honda", Year = 1892, Website = "www.honda.jp"} };
    
    List<Factory> factories = new List<Factory>() {     new Factory() { Name = "Ferrari", Website = "www.ferrari.it" }, 
                                                        new Factory() { Name = "Jaguar", Website = "www.jaguar.co.uk" }, 
                                                        new Factory() { Name = "BMW", Website = "www.bmw.de"} };
    
    foreach (Car car in cars.Where(c => !factories.Any(f => f.Name == c.Name))) {
        lblDebug.Text += car.Name;
    }
    
    0 讨论(0)
  • 2021-02-01 03:10

    Well, you already have good answers, but they're most Lambda. A more LINQ approach would be like

    var NotSentMessages =
                    from msg in MsgList
                    where !SentList.Any(x => x.MsgID == msg.MsgID)
                    select msg;
    
    0 讨论(0)
  • 2021-02-01 03:11

    As an extension method

    public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector) 
    {
        var targetValues = new HashSet<TKey>(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<Customer>()
    {
        new Customer() { CustomerId = 1 },
        new Customer() { CustomerId = 2 }
    };
    
    var others = new List<OtherCustomer>()
    {
        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);
    
    0 讨论(0)
  • 2021-02-01 03:19

    If u wanna Select items of List from 2nd list:

    MainList.Where(p => 2ndlist.Contains(p.columns from MainList )).ToList();

    0 讨论(0)
提交回复
热议问题