我正在尝试实现允许比较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?
答案 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
我希望这有助于你