C# Update a List from Another List

后端 未结 5 1384
别跟我提以往
别跟我提以往 2020-12-16 12:50

I have 2 List. The first one, lets call it ListA is more like a complete list and the second one ListB is a modified list. Now what I want to do i
相关标签:
5条回答
  • 2020-12-16 13:18

    You could also use the Union method with an IEqualityComparer:

    var newList = ListB.Union(ListA, new PersonEqualityComparer());
    
    class PersonEqualityComparer : IEqualityComparer<Person>
    {
        public bool Equals(Person person1, Person person2)
        {
            if (person1 == null && person2 == null)
                return true;
            else if ((person1 != null && person2 == null) ||
                    (person1 == null && person2 != null))
                return false;
    
            return person1.Id.Equals(person2.Id);
        }
    
        public int GetHashCode(Person item)
        {
            return item.Id.GetHashCode();
        }
    }
    
    0 讨论(0)
  • 2020-12-16 13:21

    As I consider, you want to update only an age. Also you don't need to use Where().First() you can use just First().

    foreach (var x in ListB)
    {
        var itemToChange = ListA.First(d => d.Name == x.Name).Age = x.Age;
    }
    

    If you are not sure, that item exists in ListA you should use FirstOrDefault() and if statement to check it.

    foreach (var x in ListB)
    {
        var itemToChange = ListA.FirstOrDefault(d => d.Name == x.Name);
        if (itemToChange != null)
             itemToChange.Age = x.Age;
    }
    
    0 讨论(0)
  • 2020-12-16 13:23

    to elaborate aershov's answer:

    ListA.Where(d => d.Name == x.Name).First().CopyFrom(x);
    

    then in your Person class:

    public class Person
    {
       // ... Name, Id, Age properties...
    
       public void CopyFrom(Person p)
       {
          this.Name = p.Name;
          this.Id = p.Id;
          this.Age = p.Age;
       }
    }
    

    of course check nulls and everything.

    0 讨论(0)
  • 2020-12-16 13:28

    Where and First return IEnumerable - you can modify only node of the list, but not reassign.

    option 0 - generic approach

    using System.Collections.Generic;
    
    //...
    
       var itemToUpdate = ListA.FirstOrDefault(d => d.Name == x.Name);
       if (itemToUpdate != null) {
           ListA[ListA.IndexOf(itemToUpdate)] = x;
       }
    

    option 1 - implement the update method or perform field update manually

    ListA.First(d => d.Name == x.Name).Update(x);
    
    0 讨论(0)
  • 2020-12-16 13:34

    You could remove all elements of ListB from ListA based on Id, add ListB to ListA and then sort using Id.

    var newlist = ListA.Where(s => !ListB.Any(p => p.Id == s.Id)).ToList();
    newlist.AddRange(ListB);
    ListA = newlist.OrderBy(o => o.Id).ToList();
    
    0 讨论(0)
提交回复
热议问题