Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

.net - insert into a List alphabetically 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.

Sample Code:

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);
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
}

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);

If you are limited to usinf .NetFramework3.5, you could use SortedList<TKey, TValue> Class then:

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...