简体   繁体   English

在C#中实现对象列表的排序以及更改对象索引的方法

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

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. 我想要的是创建一个可以使用名为OrderIndex的属性进行排序的列表。 So I add this property to the Person object: 因此,我将此属性添加到Person对象:

{
  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. 此OrderIndex属性的目的是将Person对象在列表中的特定索引处放置,以使Person对象的排名更高。

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 因为说我有3个人物

Name: Dave, Gender: Male, OrderIndex: 1 Name: Amanda, Gender: Female, OrderIndex: 2 Name: Trevor, Gender: Male, OrderIndex: 3 名称:戴夫(Dave),性别:男,OrderIndex:1名称:Amanda,性别:女,OrderIndex:2名称:Trevor,性别:男,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. 如果我递减Trevor的OrderIndex,我还必须确保Amandas OrderIndex递增,以使没有两个具有相同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? 我应该如何解决这个问题?

If you change an OrderIndex you have to find the next integer which is free. 如果更改OrderIndex,则必须找到下一个免费的整数。 So if you change Trevors OrderIndex to 2, you have to search the next free int for Amandas OrderIndex. 因此,如果将Trevors OrderIndex更改为2,则必须在下一个可用的int中搜索Amandas OrderIndex。 So create a method where this is done. 因此,创建一个完成此操作的方法。

Here's how you search next free int: get next available integer using LINQ 这是搜索下一个可用的int的方法: 使用LINQ获取下一个可用的整数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM