问题
Say I have a list of object Person
{
public string Name {get; set;}
public string Gender {get; set;}
}
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;}
}
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.
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
Name: Dave, Gender: Male, OrderIndex: 1 Name: Amanda, Gender: Female, OrderIndex: 2 Name: Trevor, Gender: Male, OrderIndex: 3
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?
回答1:
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.
Here's how you search next free int: get next available integer using LINQ
来源:https://stackoverflow.com/questions/56985719/implementing-ordering-for-list-of-objects-in-c-sharp-and-methods-for-changing-th