In C#, data structures are used to store and manipulate data efficiently. C# provides several built-in data structures and allows us to create custom data structures using classes and structs. Some of the commonly used data structures in C# include: 1. Arrays: Arrays are fixed-size collections of elements of the same data type. They provide efficient random access to elements. Example:
int[] numbers = new int[5]; numbers[0] = 10;
2. Lists: Lists are dynamic arrays that can grow or shrink in size. They are part of the System.Collections.Generic namespace. Example: List<int> numbersList = new List<int>(); numbersList.Add(10); 3. Queues and Stacks: These are collections used to manage data in a first-in-first-out (FIFO) or last-in-first-out (LIFO) manner, respectively. They are also part of the System.Collections.Generic namespace. Example: Queue<int> queue = new Queue<int>(); Stack<int> stack = new Stack<int>(); 4. Dictionaries: Dictionaries store key-value pairs and allow you to quickly look up values by their associated keys. They are part of the System.Collections.Generic namespace. Example: Dictionary<string, int> ages = new Dictionary<string, int>(); ages["Alice"] = 25; 5. Sets: Sets store unique elements and are useful for maintaining a collection of distinct values. They are part of the System.Collections.Generic namespace. Example: HashSet<int> uniqueNumbers = new HashSet<int>(); uniqueNumbers.Add(10); 6. LinkedList: A linked list is a data structure where each element points to the next element in the list. It allows for efficient insertions and deletions but slower random access. Example: LinkedList<int> linkedList = new LinkedList<int>(); linkedList.AddLast(10); 7. SortedSet and SortedDictionary: These data structures are similar to sets and dictionaries, respectively, but keep their elements sorted in a specific order. They are part of the System.Collections.Generic namespace. Example: SortedSet<int> sortedSet = new SortedSet<int>(); SortedDictionary<string, int> sortedDictionary = new SortedDictionary<string, int>(); 8. Custom Data Structures: You can create your own custom data structures by defining classes or structs to encapsulate the data and operations you need. These are just a few examples of data structures available in C#. The choice of data structure depends on the specific requirements of your application and the operations you need to perform on the data.
Comments
Post a Comment