我有一个对象列表如下:
ID Name PageOrder
1 Home 1
2 Product 2
3 Link 3
4 Help 4
所需:
ID Name PageOrder
1 Home 1
3 Link 2
2 Product 3
4 Help 4
我在C#编码如下。但我不认为我的方式不是最好的实践。 请建议。
public void OrderUp(int favouriteId)
{
UsFavourite currentFav = db.UsFavourites.FirstOrDefault(m => m.FavouriteID == favouriteId);
// Get favourite by current favourite's order - 1
UsFavourite tempFav = db.UsFavourites.FirstOrDefault(m => m.FavouriteOrder == (currentFav.FavouriteOrder - 1));
if (tempFav != null)
{
//update tempFav
tempFav.FavouriteOrder = currentFav.FavouriteOrder;
Save();
//update currentFav
currentFav.FavouriteOrder = currentFav.FavouriteOrder - 1;
Save();
}
}
public void OrderDown(int favouriteId)
{
UsFavourite currentFav = db.UsFavourites.FirstOrDefault(m => m.FavouriteID == favouriteId);
// Get favourite by current favourite's order + 1
UsFavourite tempFav = db.UsFavourites.FirstOrDefault(m => m.FavouriteOrder == (currentFav.FavouriteOrder + 1));
if (tempFav != null)
{
//update tempFav
tempFav.FavouriteOrder = currentFav.FavouriteOrder;
Save();
//update currentFav
currentFav.FavouriteOrder = currentFav.FavouriteOrder + 1;
Save();
}
}
答案 0 :(得分:3)
代码看起来很好。保罗说你不应该使用保存两次。我也很想通过以下
删除一些重复 public void OrderUp(int favouriteId)
{
ChangeOrder(false, favouriteId);
}
public void OrderDown(int favouriteId)
{
ChangeOrder(true, favouriteId);
}
private void ChangeOrder(bool OrderDown, int favouriteId)
{
UsFavourite currentFav = db.UsFavourites.FirstOrDefault(m => m.FavouriteID == favouriteId);
// Get favourite by current favourite's order + 1
UsFavourite tempFav;
if (OrderDown)
{
tempFav = db.UsFavourites.OrderBy(m => m.FavouriteOrder).FirstOrDefault(m => m.FavouriteOrder > (currentFav.FavouriteOrder));
}
else
{
tempFav = db.UsFavourites.OrderByDescending(m => m.FavouriteOrder).FirstOrDefault(m => m.FavouriteOrder < (currentFav.FavouriteOrder));
}
if (tempFav != null)
{
//update tempFav
tempFav.FavouriteOrder = currentFav.FavouriteOrder;
//update currentFav
currentFav.FavouriteOrder = currentFav.FavouriteOrder + change;
Save();
}
}