Implementing ordering for List of objects in C# and methods for changing the index of the object

烂漫一生 提交于 2020-04-30 07:59:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!