📜  c# iorderedenumerable to dictionary - C# (1)

📅  最后修改于: 2023-12-03 15:29:45.771000             🧑  作者: Mango

C# IOrderedEnumerable to Dictionary

In C#, IOrderedEnumerable is a collection that contains a sorted sequence of elements. Sometimes, we need to convert this sorted collection to a dictionary for faster access and better performance. This post will guide you through how to convert an IOrderedEnumerable collection to a dictionary in C#.

Converting IOrderedEnumerable to Dictionary

To convert an IOrderedEnumerable collection to a dictionary, we can use the following syntax:

var dictionary = orderedEnumerable.ToDictionary(key => key.SomeKey, value => value.SomeValue);

where SomeKey and SomeValue are properties in our sorted collection that we want to use as the key and value for our dictionary.

Here is an example:

class Student {
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

var students = new List<Student>() {
    new Student() {Id = 1, Name = "John", Age = 25},
    new Student() {Id = 2, Name = "Jane", Age = 23},
    new Student() {Id = 3, Name = "Max", Age = 20}
};

var sortedStudents = students.OrderBy(s => s.Name);

var studentDictionary = sortedStudents.ToDictionary(s => s.Id, s => s);

In this example, we first create a list of students, then we sort it by their names. Next, we create a dictionary where the key is the student's Id and the value is the entire student object. Now, we can access any student object by their Id with O(1) complexity.

Conclusion

Converting an IOrderedEnumerable collection to a dictionary is a useful technique in C#. By following the above syntax and examples, you can quickly and easily convert your sorted collection to a dictionary for faster access and better performance.

Reference