Linq for 2 collection simultaneously

前端 未结 3 1682
天命终不由人
天命终不由人 2021-01-20 16:41
相关标签:
3条回答
  • 2021-01-20 16:47

    You can use this one liner:

    List<A> result = listA1.Where((t, i) => t.ModifiedDate != listA2[i].ModifiedDate).ToList();
    
    0 讨论(0)
  • 2021-01-20 16:47

    You could use listA1.Except(listA2, cmp) where cmp is an IComparer. Something like:

    void Main()
    {
        List<A> listA1 = new List<A> {
           new A { Id=1, ModifiedDate=new DateTime(2016,1,1), Type="A"},
           new A { Id=2, ModifiedDate=new DateTime(2016,1,2), Type="A"},
           new A { Id=3, ModifiedDate=new DateTime(2016,1,3), Type="A"},
           new A { Id=4, ModifiedDate=new DateTime(2016,1,4), Type="A"},
        };
        List<A> listA2 = new List<A> {
           new A { Id=1, ModifiedDate=new DateTime(2016,1,1), Type="A"},
           new A { Id=2, ModifiedDate=new DateTime(2016,1,2), Type="A"},
           new A { Id=3, ModifiedDate=new DateTime(2016,1,3), Type="A"},
           new A { Id=4, ModifiedDate=new DateTime(2016,1,5), Type="A"},
           new A { Id=5, ModifiedDate=new DateTime(2016,1,6), Type="A"},
           new A { Id=6, ModifiedDate=new DateTime(2016,1,7), Type="A"},
        };
    
        var cmp = new AEqualityComparer();
        var result = listA1.Except(listA2, cmp);
    
        foreach (var item in result)
        {
            Console.WriteLine("Id:{0}, Date:{1}",item.Id, item.ModifiedDate);
        }
    }
    
    public class A
    {
        public int Id { get; set; }
        public DateTime ModifiedDate { get; set; }
        public string Type { get; set; }
    }
    
    public class AEqualityComparer : IEqualityComparer<A>
    {
        public bool Equals(A x, A y)
        {
            return x.Id == y.Id && x.ModifiedDate == y.ModifiedDate;
        }
    
        public int GetHashCode(A obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
    
    0 讨论(0)
  • 2021-01-20 17:06

    You can use Enumerable.Zip to link two sequences by index:

    List<A> result = listA1.Zip(listA2, (a1, a2) => new { a1, a2 })
        .Where(x => x.a1.ModifiedDate != x.a2.ModifiedDate)
        .Select(x => x.a1)
        .ToList();
    

    This will work even if both sequences don't implement IList/IList<T>, so the items can't be accessed by index.

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