按字母顺序插入列表C#

Jay*_*ave 14 .net c#

任何人都可以教我如何在C#中按字母顺序将项目插入列表?

因此,每次我添加到列表中时,我都希望在列表中添加一个项目,理论上列表可能会变得非常大.

示例代码:

Public Class Person
{
     public string Name { get; set; }
     public string Age { get; set; }
}

Public Class Storage
{
    private List<Person> people;

    public Storage
    {
        people = new List<Person>();
    }


    public void addToList(person Person)
    {
        int insertIndex = movies.findindex(
            delegate(Movie movie) 
            {
              return //Stuck here, or Completely off Track.

            }
        people.insert(insertIndex, newPerson);
    }

}
Run Code Online (Sandbox Code Playgroud)

hor*_*rgh 10

定义比较器实现IComparer<T>接口:

public class PersonComparer : IComparer<Person>
{
    public int Compare(Person x, Person y)
    {
        return x.Name.CompareTo(y.Name);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用SortedSet<T>Class:

        SortedSet<Person> list = new SortedSet<Person>(new PersonComparer());
        list.Add(new Person { Name = "aby", Age = "1" });
        list.Add(new Person { Name = "aab", Age = "2" });
        foreach (Person p in list)
            Console.WriteLine(p.Name);
Run Code Online (Sandbox Code Playgroud)

如果您仅限于使用.NetFramework3.5,则可以使用SortedList<TKey, TValue>Class:

SortedList<string, Person> list = 
          new SortedList<string, Person> (StringComparer.CurrentCulture);
Person person = new Person { Name = "aby", Age = "1" };
list.Add(person.Name, person);
person = new Person { Name = "aab", Age = "2" };
list.Add(person.Name, person);

foreach (Person p in list.Values)
    Console.WriteLine(p.Name);
Run Code Online (Sandbox Code Playgroud)

请仔细阅读MSDN artcile中的Remarks部分,比较此类和SortedDictionary<TKey, TValue>Class


小智 5

如果您绝对想使用列表,请尝试以下操作:

int loc;
for(loc = 0; loc < people.Count && people[loc].Name.CompareTo(personToInsert.Name) < 0; loc++);
people.Insert(loc, personToInsert);
Run Code Online (Sandbox Code Playgroud)

您可以替换people[loc].Name.CompareTo(personToInsert.Name) < 0为您正在测试的任何条件 - 您可以更改符号以使其下降而不是上升。就像people[loc].Age < personToInsert.Age例如会按年龄排序。


Ara*_*ami 5

旧线程,但此线程的答案IMO忽略了OP的实际问题。问题很简单-如何按已排序的顺序插入列表。这与“仅使用SortedSet / SortedList”不同。根据下面的使用与使用SortedList的使用,会有不同的特征和含义。

SortedSet和SortedList都基于Dictionary,并且不允许您添加两个具有相同键AFAIK的项。

那么如何计算{a,b,c,c,d}这样的列表呢?

这是插入到有序列表中以便项目保持有序的正确方法:

var binarySearchIndex = list.BinarySearch(item, itemComparer);
//The value will be a negative integer if the list already 
//contains an item equal to the one searched for above
if (binarySearchIndex < 0)
{
    list.Insert(~binarySearchIndex, item);
}
else
{
    list.Insert(binarySearchIndex, item);
}
Run Code Online (Sandbox Code Playgroud)

通过2010年的这篇出色文章来回答:https : //debugmode.net/2010/09/18/inserting-element-in-sorted-generic-list-list-using-binary-search/