17

谁能教我如何在 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);
    }

}
4

5 回答 5

12

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

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

然后使用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);

如果您仅限于使用 .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);

特别是阅读MSDN 文章中的备注部分,比较这个类和SortedDictionary<TKey, TValue>

于 2012-11-01T04:27:30.293 回答
10

旧线程,但这个线程 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);
}

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

于 2017-06-07T23:54:31.063 回答
5

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

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

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

于 2014-07-16T20:56:21.320 回答
2

看看SortedSet<T>课堂。只需使用它而不是List<T>.

于 2012-11-01T04:26:36.563 回答
2

SortedList是你所需要的。创建一个 StringComparer 对象并将其传递给 sortedlist 的构造函数。元素在插入新项目时自动排序。

StringComparer stringComp = StringComparer.CurrentCulture;
SortedList sl = new SortedList(stringComp);
sl.Add("B", "SECOND");
sl.Add("A", "FIRST");
sl.Add("C", "THIRD");
于 2012-11-01T04:33:10.007 回答