按字母顺序插入到列表中的C# [英] insert into a List alphabetically C#

查看:70
本文介绍了按字母顺序插入到列表中的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Could anyone please teach me how to insert item into list in alphabetical order in C#?

因此,每次我添加到列表中时,我都想按字母顺序添加一个项目,从理论上讲,列表可能会变得很大.

So every time I add to the list I want to add an item alpabetically, the list could become quite large in theory.

示例代码:

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> 接口:

Define a comparer implemeting IComparer<T> Interface:

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

并使用 SortedSet< T> 然后:

And use SortedSet<T> Class then:

        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> 然后:

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>

Espesially read the Remarks section in the MSDN artcile, comparing this class and SortedDictionary<TKey, TValue> Class

这篇关于按字母顺序插入到列表中的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆