我们说我有一个班级:
public class User{
public string Name {get;set;}
public int SeqNumber {get;set;}
}
public List<User> UserClass {get;set;}
对于动态示例,我有10个用户。每个SeqNumber都是唯一的,从1到10,基于用户数量。 SeqNumber将用于按升序对用户进行排序。但是,SeqNumber必须是唯一的,并且仍在用户数量的范围内。
UserClass = new List<User>() {
new User({Name = "Rose", SeqNumber = 1}),
new User({Name = "Ryu", SeqNumber = 2}),
new User({Name = "Sagat", SeqNumber = 3}),
new User({Name = "Dhalsim", SeqNumber = 4}),
new User({Name = "Zangief", SeqNumber = 5}),
new User({Name = "Ken", SeqNumber = 6}),
new User({Name = "Chun-Li", SeqNumber = 7}),
new User({Name = "Vega", SeqNumber = 8}),
new User({Name = "Balrog", SeqNumber = 9}),
new User({Name = "M. Bison", SeqNumber = 10}),
};
让我们说有人决定将Ryu的SeqNumber更改为6,作为使用示例。 Sagat将升至2,Dhalsim将升至3,Zangief将升至4,Ken将升至5。 反过来,如果我将M.Bison的SeqNumber移动到2怎么办?其他用户的SeqNumber应该增加1.如何实现?
答案 0 :(得分:1)
您可以使用以下扩展方法来执行此操作,该方法在列表中使用索引器:
public static void MoveAndRecalculateSequence(
this IList<User> users, int moveFromIndex, int moveToIndex)
{
// Capture a reference to the user we want to move.
var user = users[moveFromIndex];
// Remove it from the list at it's current index.
users.RemoveAt(moveFromIndex);
// Insert the user at the required destination.
users.Insert(moveToIndex, user);
// Recalculate the seq number using the index of the list.
for(int i = 0; i < users.length; i++)
{
users[i].SeqNumber = i + 1;
}
}
并按原样使用:
// remember indexes start at 0 in C#
users.MoveAndRecalculateSequence(1, 5);
答案 1 :(得分:-1)
将您的用户放入列表中,以便您可以动态访问它们:
UserClass = new List<User>() {
new User({Name = "xxxx", SeqNumber = 1}),
new User({Name = "xxxx", SeqNumber = 2}),
new User({Name = "xxxx", SeqNumber = 3}),
...
};
现在,您可以获取应更改SeqNumber
属性的用户,即数字为2到6的用户,并为其设置新值:
UserClass
.Where(u => u.SeqNumber => 2 && u.SeqNumber <= 6)
.ToList()
.ForEach(u => {
if (u.SeqNumber == 2) {
u.SeqNumber = 6
} else {
u.SeqNumber--;
}
});