C#Linq将一个列表<custom>中的元素添加到另一个列表中,将它们与更改值进行比较

时间:2017-06-25 08:39:35

标签: c# list linq compare ienumerable

我正在尝试实现允许比较2个列表的功能,如果两者中都有相同的值(id),则第二个列表将覆盖第一个列表中的元素值,否则将添加第二个列表中的元素< / p>

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);
            }
        }
    }
}

有没有更有效的方式来做而不是foreach?

1 个答案:

答案 0 :(得分:0)

试试这个:

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();
}

在main方法中:

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());

结果将包含4个元素:  1 Ted,2 Jhon,3 Alex,4 Sam

我希望这有助于你