【问题标题】:C# Linq add elements from one list<custom> to another comparing them and changing valuesC# Linq 将一个列表中的元素添加到另一个列表中,比较它们并更改值
【发布时间】:2017-11-28 09:44:10
【问题描述】:

我试图实现允许比较 2 个列表的功能,如果两者中的值 (id) 相同,则第二个列表将覆盖第一个列表中的元素值,否则将添加第二个列表中的元素

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 更有效的方法?

【问题讨论】:

  • 欢迎来到 Stack Overflow!您的代码目前似乎可以运行,并且您正在寻求改进它。一般来说,这些问题对于本网站来说过于固执己见,但您可能会在CodeReview.SE 找到更好的运气。记得阅读their requirements,因为他们比这个网站更严格。
  • 您可以通过 PotionManager.Potion.Eff.id 创建一个 ISet(例如 HashSet)以使用 SomeSet.Contains(_eff.id) 而不是 effs.Find(x =&gt; x.id == _eff.id) 来提高性能
  • 您可以尝试使用 IEqualityComparer 接口,只需使用“Except”或“Intersect”方法进行所有比较并删除 foreach 请参阅相同的 MSDN 文档:msdn.microsoft.com/en-us/library/ms132151(v=vs.110).aspx

标签: c# list linq compare ienumerable


【解决方案1】:

试试这个:

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

在主方法中:

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 泰德,2 乔恩,3 亚历克斯,4 萨姆

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2022-02-08
    相关资源
    最近更新 更多