按字母顺序插入列表C#

前端之家收集整理的这篇文章主要介绍了按字母顺序插入列表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);
    }

}

解决方法

定义一个比较器实现 IComparer<T> Interface
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 artcile中的备注部分,比较此类和SortedDictionary<TKey,TValue> Class

原文链接:https://www.f2er.com/csharp/96248.html

猜你在找的C#相关文章