有人可以教我如何在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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。