i试图实现允许比较2个列表的功能,如果这两个都有相同的值(id(,第二个列表将叠加该元素值在第一个列表中,else else第二列表中的元素将添加
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?
尝试以下:
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 Ted,2 Jhon,3 Alex,4 Sam
我希望这对您有帮助