简体   繁体   中英

C# Linq add elements from one list<custom> to another comparing them and changing values

I was trying to implement functionality that allows 2 lists to be compared, and if there is a identical value (id) in both, second list will overlay that element values in first list, else element from second list will be added

private List<PotionManager.Potion.Eff> effs = new List<PotionManager.Potion.Eff>();

public string id
{
    set
    {
        var _effs = new List<PotionManager.Potion.Eff>(PM.GetEffectsOnPotion(value).Select(x => x.Clone()));
        foreach (PotionManager.Potion.Eff _eff in _effs)
        {
            var eff = effs.Find(x => x.id == _eff.id);
            if (eff != null)
            {
                eff.power = _eff.power;
                eff.time = _eff.time;
            }
            else
            {
                effs.Add(_eff);
            }
        }
    }
}

is there a more efficient way doing that instead of foreach?

try this:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class UserComparer : IEqualityComparer<User>
{
    public bool Equals(User x, User y) => x.Id == y.Id;
    public int GetHashCode(User obj) => base.GetHashCode();
}

in main method:

var list1 = new List<User>
    {
        new User{Id = 1, Name = "Ted" },
        new User{Id = 2, Name = "Jhon" },
        new User{Id = 3, Name = "Alex" }
    };
var list2 = new List<User>
    {
        new User{Id = 2, Name = "Jhon" },
        new User{Id = 3, Name = "Alex" },
        new User{Id = 4, Name = "Sam" },
    };

var result = list1.Union(list2, new UserComparer());

the result will contains 4 elements: 1 Ted, 2 Jhon, 3 Alex, 4 Sam

I hope this helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM