按字母顺序插入列表C#

前端之家收集整理的这篇文章主要介绍了按字母顺序插入列表C#前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以教我如何在C#中按字母顺序将项目插入列表中?

所以每当我添加到列表中,我想添加一个项目,这个列表在理论上可能变得相当大.

示例代码

  1. Public Class Person
  2. {
  3. public string Name { get; set; }
  4. public string Age { get; set; }
  5. }
  6.  
  7. Public Class Storage
  8. {
  9. private List<Person> people;
  10.  
  11. public Storage
  12. {
  13. people = new List<Person>();
  14. }
  15.  
  16.  
  17. public void addToList(person Person)
  18. {
  19. int insertIndex = movies.findindex(
  20. delegate(Movie movie)
  21. {
  22. return //Stuck here,or Completely off Track.
  23.  
  24. }
  25. people.insert(insertIndex,newPerson);
  26. }
  27.  
  28. }

解决方法

定义一个比较器实现 IComparer<T> Interface
  1. public class PersonComparer : IComparer<Person>
  2. {
  3. public int Compare(Person x,Person y)
  4. {
  5. return x.Name.CompareTo(y.Name);
  6. }
  7. }

然后使用SortedSet<T> Class

  1. SortedSet<Person> list = new SortedSet<Person>(new PersonComparer());
  2. list.Add(new Person { Name = "aby",Age = "1" });
  3. list.Add(new Person { Name = "aab",Age = "2" });
  4. foreach (Person p in list)
  5. Console.WriteLine(p.Name);

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

  1. SortedList<string,Person> list =
  2. new SortedList<string,Person> (StringComparer.CurrentCulture);
  3. Person person = new Person { Name = "aby",Age = "1" };
  4. list.Add(person.Name,person);
  5. person = new Person { Name = "aab",Age = "2" };
  6. list.Add(person.Name,person);
  7.  
  8. foreach (Person p in list.Values)
  9. Console.WriteLine(p.Name);

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

猜你在找的C#相关文章