问题描述
说我有一个对象Person的列表
Say I have a list of object Person
{
public string Name {get; set;}
public string Gender {get; set;}
}
我想要的是创建一个可以使用名为OrderIndex的属性进行排序的列表.因此,我将此属性添加到Person对象:
What I want is to create a List that I can order by using a property called OrderIndex. So I add this property to the Person object:
{
public string Name {get; set;}
public string Gender {get; set;}
public int OrderIndex {get; set;}
}
此OrderIndex属性的目的是将Person对象在列表中的特定索引处放置,以使Person对象的排名更高.
The purpose of this OrderIndex property is to place the Person object in the list at a specific index for ranking the Person object higher.
但是,我对此感到非常担忧,因为我必须坚持逻辑的数量.因为说我有3个人物
But I am very concerned about the amount of logic that I have to implenent because of this. Because say I have 3 person objects
名称:Dave,性别:男性,OrderIndex:1姓名:阿曼达(Amanda),性别:女,订单号:2姓名:Trevor,性别:男性,OrderIndex:3
Name: Dave, Gender: Male, OrderIndex: 1Name: Amanda, Gender: Female, OrderIndex: 2Name: Trevor, Gender: Male, OrderIndex: 3
如果我递减Trevor的OrderIndex,我还必须确保将Amandas OrderIndex递增,以使没有两个具有相同OrderIndex的人对象.
If I decrement the OrderIndex of Trevor, I will also have to make sure, that Amandas OrderIndex is incremented as to not have two person objects with the same OrderIndex.
我不确定以前是否已经回答过这个问题,但是我没有运气找到要回答该问题的特定线程.
I'm not sure if this question has been answered here before, but I haven't had any luck finding a specific thread to where this has been answered.
我应该如何解决这个问题?
How should I approach this problem?
推荐答案
如果更改OrderIndex,则必须找到下一个自由的整数.因此,如果将Trevors OrderIndex更改为2,则必须在下一个可用的int中搜索Amandas OrderIndex.因此,创建一个完成此操作的方法.
If you change an OrderIndex you have to find the next integer which is free. So if you change Trevors OrderIndex to 2, you have to search the next free int for Amandas OrderIndex. So create a method where this is done.
以下是搜索下一个免费int的方法:使用LINQ获取下一个可用整数
Here's how you search next free int:get next available integer using LINQ
这篇关于在C#中实现对象列表的排序以及更改对象索引的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!