You are previewing Developer’s Guide to Collections in Microsoft® .NET.
O'Reilly logo
Developer’s Guide to Collections in Microsoft® .NET

Book Description

Build the skills to apply Microsoft .NET collections effectively

Put .NET collections to work—and manage issues with GUI data binding, threading, data querying, and storage. Led by a data collection expert, you'll gain task-oriented guidance, exercises, and extensive code samples to tackle common problems and improve application performance. This one-stop reference is designed for experienced Microsoft Visual Basic and C# developers—whether you’re already using collections or just starting out.

Discover how to:

  • Implement arrays, associative arrays, stacks, linked lists, and other collection types

  • Apply built in .NET collection classes by learning their methods and properties

  • Add enumerator, dictionary, and other .NET collection interfaces to your classes

  • Query collections by writing simple to complex Microsoft LINQ statements

  • Synchronize data across threads using built in .NET synchronization classes

  • Enhance your custom collection classes with serialization support

  • Use simple data binding to display collections in Windows Forms, Microsoft Silverlight, and Windows Presentation Foundation

  • Table of Contents

    1. Developer’s Guide to Collections in Microsoft® .NET
    2. A Note Regarding Supplemental Files
    3. Introduction
      1. Who Should Read This Book
        1. Assumptions
      2. Who Should Not Read This Book
      3. Organization of This Book
        1. Part I, Collection Basics
        2. Part II, .NET Built-in Collections
        3. Part III, Using Collections
        4. Part IV, Using Collections with UI Controls
        5. Finding Your Best Starting Point in This Book
      4. Conventions and Features in This Book
      5. System Requirements
      6. Code Samples
        1. Installing the Code Samples
        2. Using the Code Samples
      7. Acknowledgments
      8. Errata & Book Support
      9. We Want to Hear from You
      10. Stay in Touch
    4. I. Collection Basics
      1. 1. Understanding Collections: Arrays and Linked Lists
        1. Array Overview
          1. Uses of Arrays
          2. Advantages of Arrays
          3. Disadvantages of Arrays
        2. Array Implementation
          1. Understanding Indexing
          2. Getting Started
          3. Creating Constructors
          4. Allowing Users to Add Items
          5. Allowing Users to Remove Items
          6. Adding Helper Methods and Properties
          7. Using the ArrayEx(T) Class
        3. Linked List Overview
          1. Uses of Linked Lists
          2. Advantages of Linked Lists
          3. Disadvantages of Linked Lists
        4. Linked List Implementation
          1. Singly Linked List Implementation
            1. Creating the Node Class
            2. Declaring the SingleLinkedList(T) Class
            3. Creating Constructors
            4. Allowing Users to Add Items
            5. Allowing Users to Remove Items
            6. Adding Helper Methods and Properties
          2. Doubly Linked List Implementation
            1. Creating the Node Class
            2. Declaring the DoubleLinkedList(T) Class
            3. Creating Constructors
            4. Allowing Users to Add Items
            5. Allowing Users to Remove Items
            6. Adding Helper Methods and Properties
          3. Using an Array to Create a Linked List
          4. Using the Linked List Class
        5. Summary
      2. 2. Understanding Collections: Associative Arrays
        1. Associative Array Overview
          1. Uses of Associative Arrays
          2. Advantages and Disadvantages of Associative Arrays
        2. Associative Array Implementation
          1. Using Association Lists for Associative Arrays
            1. Advantages of Association Lists
            2. Disadvantages of Association Lists
            3. Getting Started
            4. Creating Constructors
            5. Allowing Users to Associate Values with Keys
            6. Allowing Users to Remove Keys
            7. Adding Helper Methods and Properties
          2. Using Hash Tables for Associative Arrays
            1. Advantages of Hash Tables
            2. Disadvantages of Hash Tables
            3. Understanding Hash Table Buckets
            4. Understanding Hash Table Collisions
            5. Understanding Chaining
            6. Understanding Object.GetHashCode
            7. Picking a Hashing Function
            8. Picking a Good Number of Buckets
            9. Implementing Your Internal Storage
            10. Getting Started
            11. Creating the Constructor
            12. Allowing Users to Associate Values with Keys
            13. Allowing Users to Remove Keys
            14. Adding Helper Methods and Properties
          3. Using the Associative Array Class
        3. Summary
      3. 3. Understanding Collections: Queues, Stacks, and Circular Buffers
        1. Queue Overview
          1. Uses of Queues
        2. Queue Implementation
          1. Using an Array to Implement a Queue
            1. Creating Constructors
            2. Allowing Users to Add Items
            3. Allowing Users to Remove Items
            4. Adding Helper Methods and Properties
          2. Using a Linked List to Implement a Queue
            1. Creating Constructors
            2. Allowing Users to Add Items
            3. Allowing Users to Remove Items
            4. Adding Helper Methods and Properties
          3. Using the Queue Classes
        3. Stack Overview
          1. Uses of Stacks
        4. Stack Implementation
          1. Adding the Common Functionality
          2. Using an Array to Implement a Stack
            1. Creating Constructors
            2. Allowing Users to Add to Items
            3. Allowing Users to Remove Items
            4. Adding Helper Methods
          3. Using a Linked List to Implement a Stack
            1. Creating Constructors
            2. Allowing Users to Add Items
            3. Allowing Users to Remove Items
            4. Adding Helper Methods
          4. Using the Stack Classes
        5. Circular Buffer Overview
          1. Uses of Circular Buffers
        6. Circular Buffer Implementation
          1. Getting Started
          2. Understanding the Internal Storage
          3. Creating Constructors
          4. Allowing Users to Add Items
          5. Allowing Users to Remove Items
          6. Adding Helper Methods and Properties
          7. Changing Capacity
            1. When the Start Is Smaller Than the End
            2. When the Start Is Larger Than the End
          8. Using the CircularBuffer(T) Class
        7. Summary
    5. II. .NET Built-in Collections
      1. 4. Generic Collections
        1. Understanding the Equality and Ordering Comparers
          1. Understanding the Equality Comparer
            1. How Reference Equality Works
            2. How Bitwise Equality Works
          2. Understanding the Ordering Comparer
        2. Understanding Delegates, Anonymous Methods, and Lambda Expressions
          1. Lambda Expressions in Visual Basic
        3. List(T) Overview
        4. Using the List(T) Class
          1. Creating a List(T)
            1. List(T)()
            2. List(T)(IEnumerable(T) collection)
            3. List(T)(int size)
          2. Appending Items to a List(T)
            1. void Add(T item)
            2. void AddRange(IEnumerable(T) collection)
          3. Traversing a List(T)
            1. The foreach Statement
            2. void ForEach(Action(T) action)
              1. Using a Method for the Action(T) Argument
              2. Using a Lambda Expression for the Action(T) Method
          4. Removing Items from a List(T)
            1. void Clear()
            2. bool Remove(T item)
            3. int RemoveAll(Predicate(T) match)
              1. Using a Method with RemoveAll
              2. Using a Lambda Expression with RemoveAll
            4. void RemoveAt(int index)
            5. void RemoveRange(int index, int count)
          5. Inserting Items into a List(T)
            1. void Insert(int index, T item)
            2. void InsertRange(int index, IEnumerable collection)
          6. Sorting a List(T)
            1. How Built-in Sorting Works
            2. void Sort()
            3. void Sort(Comparison(T) comparison)
              1. Using a Lambda Expression for the Comparison(T)
              2. Using a Method for the Comparison(T)
            4. void Sort(IComparer(T) comparer)
            5. void Sort(int index, int count, IComparer(T) comparer)
          7. Searching a List(T)
            1. T Find(Predicate(T) match) and T FindLast(Predicate(T) match)
              1. Using a Lambda Expression for the Search
              2. Using a Method for the Search
            2. FindIndex and FindLastIndex
              1. int FindIndex(Predicate(T) match)
              2. int FindLastIndex(Predicate(T) match)
                1. Using a Method to Do the Matching
                2. Using a Lambda Expression to Do the Matching
              3. int FindIndex(int startIndex, Predicate(T) match)
              4. int FindLastIndex(int startIndex, Predicate(T) match)
                1. Using a Method to Do the Matching
                2. Using a Lambda Expression to Do the Matching
              5. int FindIndex(int startIndex, int count, Predicate(T) match)
              6. int FindLastIndex(int startIndex, int count, Predicate(T) match
                1. Using a Method to Do the Matching
                2. Using a Lambda to Do the Matching
            3. List(T) FindAll(Predicate(T) match)
              1. Using a Lambda Expression for the FindAll
              2. Using a Method for the FindAll
            4. Using a Binary Search to Do the Searching
              1. int BinarySearch(T item)
              2. int BinarySearch(T item, IComparer(T) comparer)
              3. int BinarySearch(int index, int count, T item, IComparer(T) comparer)
          8. Checking the Contents of a List
            1. int IndexOf(T item) and int LastIndexOf(T item)
            2. int IndexOf(T item, int index) and int LastIndexOf(T item, int index)
            3. int IndexOf(T item, int index, int count) and int LastIndexOf(T item, int index, int count)
            4. bool Contains(T item)
            5. bool Exists(Predicate(T) match)
              1. Using a Method to Check for Existence
              2. Using a Lambda Expression to Check for Existence
            6. bool TrueForAll(Predicate(T) match)
              1. Using a Method to See Whether All Match
              2. Using a Lambda Expression to See Whether All Match
          9. Modifying the List
            1. List(TOutput) ConvertAll(Converter(T, TOutput) converter)
              1. Using a Method to Do the Conversion
              2. Using a Lambda Expression to Do the Conversion
            2. void Reverse()
            3. void Reverse(int index, int count)
            4. void TrimExcess()
        5. LinkedList(T) Overview
        6. Using the LinkedList(T) Class
          1. Creating a New LinkedList(T)
            1. LinkedList(T)()
            2. LinkedList(T)(IEnumerable(T) collection)
          2. Adding to the LinkedList(T)
            1. void AddAfter(LinkedListNode(T) node, LinkedListNode(T) newNode)
            2. LinkedListNode(T) AddAfter(LinkedListNode(T) node, T value)
            3. void AddBefore(LinkedListNode(T) node, LinkedListNode(T) newNode)
            4. LinkedListNode(T) AddBefore(LinkedListNode(T) node, T value)
            5. LinkedListNode(T) AddFirst(T item)
            6. void AddFirst(LinkedListNode(T) node)
            7. LinkedListNode(T) AddLast (T item)
            8. void AddLast (LinkedListNode(T) node)
          3. Removing Nodes from the LinkedList(T)
            1. void Clear()
            2. bool Remove(T value)
            3. bool Remove(LinkedListNode(T) node)
            4. void RemoveFirst()
            5. void RemoveLast()
          4. Obtaining Information on the LinkedList(T)
            1. LinkedListNode(T) Find(T value) and LinkedListNode(T) FindLast(T value)
            2. LinkedListNode(T) First { get; } and LinkedListNode(T) Last { get; }
            3. int Count { get; }
            4. bool Contains(T value)
        7. Summary
      2. 5. Generic and Support Collections
        1. Queue(T) Overview
        2. Using the Queue(T) Class
          1. Creating a Queue
            1. Queue(T)()
            2. Queue(T)(IEnumerable(T))
            3. Queue(T)(int size)
          2. Adding Items to the Queue
            1. void Enqueue(T item)
          3. Removing Items from the Queue
            1. void Clear()
            2. T Dequeue()
          4. Checking the Queue
            1. T Peek()
            2. bool Contains(T item)
            3. int Count
          5. Cleaning the Queue
            1. void TrimExcess()
        3. Stack(T) Overview
        4. Using the Stack(T) Class
          1. Creating a Stack
            1. Stack(T)()
            2. Stack (T)(IEnumerable(T))
            3. Stack (T)(int size)
          2. Adding Items to the Stack
            1. void Push(T item)
          3. Removing Items from the Stack
            1. void Clear()
            2. T Pop()
          4. Checking the Stack
            1. T Peek()
            2. bool Contains(T item)
            3. int Count
          5. Cleaning the Stack
            1. TrimExcess
        5. Dictionary(TKey,TValue) Overview
        6. Understanding Dictionary(TKey,TValue) Implementation
        7. Using the Dictionary(TKey,TValue) Class
          1. Creating a Dictionary
            1. Dictionary(TKey, TValue)()
            2. Dictionary(TKey, TValue)(IDictionary(TKey, TValue) dictionary)
            3. Dictionary(TKey, TValue)(IEqualityComparer(TKey) comparer)
            4. Dictionary(TKey, TValue)(int capacity)
            5. Dictionary(TKey, TValue)(IDictionary(TKey, TValue) dictionary, IEqualityComparer(TKey) comparer)
            6. Dictionary(TKey, TValue)(int capacity, IEqualityComparer(TKey) comparer)
          2. Adding Items to a Dictionary
            1. void Add(TKey key, TValue value)
            2. TValue Item[TKey key] { set; }
          3. Removing Items from a Dictionary
            1. void Clear()
            2. bool Remove(TKey key)
          4. Retrieving Values from the Dictionary by Using a Key
            1. bool TryGetValue(TKey key, out TValue value)
            2. TValue Item[TKey key] { get; }
          5. Checking the Dictionary
            1. bool ContainsKey(TKey key)
            2. bool ContainsValue(TValue value)
            3. int Count
            4. Dictionary<TKey,TValue>.KeyCollection Keys
            5. Dictionary<TKey,TValue>.ValueCollection Values
        8. BitArray Overview
        9. Using the BitArray Class
          1. Creating a BitArray
            1. BitArray(BitArray bits)
            2. BitArray(Boolean[] values)
            3. BitArray(Byte[] bytes)
            4. BitArray(Int32 length, Boolean defaultValue)
            5. BitArray(Int32 length)
            6. BitArray(Int32[] values)
          2. Accessing Bits in the BitArray Class
            1. void Set(int index, bool value)
            2. void SetAll(bool value)
            3. bool Get(int index)
            4. bool Item[int index] {get; set; }
          3. Using the BitArray Class for Bit Operations
            1. BitArray And(BitArray value)
            2. BitArray Not()
            3. BitArray Or(BitArray value)
            4. BitArray Xor(BitArray value)
        10. CollectionBase and DictionaryBase Overview
          1. Using CollectionBase
            1. void OnValidate(object value)
            2. void OnClear() and void OnClearComplete()
            3. void OnInsert(int index, Object value) and void OnInsertComplete(int index, Object value)
            4. void OnRemove(int index, object value) and void OnRemoveComplete(int index, object value)
            5. void OnSet(int index, object oldValue, object newValue) and void OnSetComplete(int index, object oldValue, object newValue)
          2. Using DictionaryBase
            1. void OnValidate(object key, object value)
            2. void OnClear() and void OnClearComplete()
            3. void OnGet()
            4. void OnInsert(Object key, Object value) and void OnInsertComplete(Object key, Object value)
            5. void OnRemove(Object key, Object value) and void OnRemoveComplete(Object key, Object value)
            6. void OnSet(Object key, object oldValue, object newValue) and void OnSetComplete(Object key, object oldValue, object newValue)
        11. HashSet(T) Overview
        12. Using the HashSet(T) Class
          1. Creating a HashSet(T)
            1. HashSet(T) ()
            2. HashSet(T) (IEnumerable(T))
            3. HashSet(T) ( IEqualityComparer(T))
            4. HashSet(T) ( IEnumerable(T), IEqualityComparer(T))
          2. Adding Items to the HashSet(T)
            1. bool Add(T item)
          3. Removing Items from a HashSet(T)
            1. void Clear()
            2. bool Remove(T item)
            3. int RemoveWhere(Predicate(T) match)
              1. Using a Method with RemoveWhere
              2. Using a Lambda Expression with RemoveWhere
          4. Performing Set Operations on a HashSet(T)
            1. void IntersectWith(IEnumerable(T) other)
            2. bool IsProperSubsetOf(IEnumerable(T) other)
            3. bool IsProperSupersetOf(IEnumerable(T) other)
            4. bool IsSubsetOf(IEnumerable(T) other)
            5. bool IsSupersetOf(IEnumerable(T) other)
            6. bool Overlaps(IEnumerable(T) other)
            7. void UnionWith(IEnumerable(T) other)
            8. void ExceptWith(IEnumerable(T) other)
            9. bool Contains(T item)
            10. void TrimExcess()
        13. Sorted Collections Overview
          1. SortedList(TKey, TValue)
          2. SortedDictionary(TKey, TValue)
        14. Summary
    6. III. Using Collections
      1. 6. .NET Collection Interfaces
        1. Enumerators (IEnumerable and IEnumerator) Overview
        2. Adding Enumeration Support to Classes
          1. ArrayEx(T)
          2. CircularBuffer(T)
          3. SingleLinkedList(T) and DoubleLinkedList(T)
          4. QueuedArray(T)
          5. QueuedLinkedList(T)
          6. StackedArray(T)
          7. StackedLinkedList(T)
          8. AssociativeArrayAL(TKey,TValue)
          9. AssociativeArrayHT(TKey,TValue)
        3. ICollection and ICollection(T) Overview
        4. Adding Collection Support to Classes
          1. ArrayEx(T)
          2. CircularBuffer(T)
          3. SingleLinkedList(T) and DoubleLinkedList(T)
          4. QueuedArray(T)
          5. QueuedLinkedList(T)
          6. StackedArray(T)
          7. StackedLinkedList(T)
          8. AssociativeArrayAL(TKey,TValue)
          9. AssociativeArrayHT(TKey,TValue)
        5. IList and IList(T) Overview
        6. Adding IList(T) and IList Support to Classes
          1. ArrayEx(T)
        7. IDictionary(TKey,TValue) Overview
        8. Adding Key/Value Pair Support to Classes
          1. AssociativeArrayAL(TKey,TValue)
          2. AssociativeArrayHT(TKey,TValue)
        9. Summary
      2. 7. Introduction to LINQ
        1. What Is LINQ?
        2. LINQ Basics
          1. Potential LINQ Data Sources
          2. What You Should Know About Query Execution
            1. Forcing Immediate Query Execution
        3. Getting Started with LINQ
          1. Additions to the .NET Language for LINQ
            1. The var Keyword
            2. Anonymous Types
            3. Object Initialization
            4. Collection Initialization
          2. Picking a Data Source (from Clause) and Selecting Results (select Clause)
            1. The from Clause
            2. The select Clause
            3. Examples of from and select Clauses
          3. Filtering Results (the where Clause)
          4. Ordering Results (the orderby Clause)
          5. The group Clause
          6. The join Clause
            1. Inner Join
            2. Outer Join
          7. The let Clause
        4. Summary
      3. 8. Using Threads with Collections
        1. What Is a Thread?
        2. What Is Thread Synchronization?
          1. Why Should I Care About Thread Synchronization?
          2. Why Not Write Thread Synchronization Code As Needed?
        3. .NET Framework Tools for Synchronization
          1. Interlocked Operations
          2. Signaling
          3. Locking
            1. Exclusive Locks
            2. Non-Exclusive Locks
        4. Adding Synchronization Support to Your Collection Classes
          1. ICollection Revisited
          2. Getting Started
        5. SyncRoot vs. the Synchronized Wrapper Class (IsSynchronized)
        6. Using the Monitor Class
        7. Using the ReaderWriterLockSlim Class
          1. Handling Recursion
          2. Using Upgradeable Locks
        8. Implementing a Synchronized Wrapper Class
        9. Handling Collection Changes While Enumerating
        10. Synchronized Collection Classes
          1. SynchronizedCollection(T)
          2. SynchronizedKeyedCollection(T)
          3. SynchronizedReadOnlyCollection(T)
        11. Summary
      4. 9. Serializing Collections
        1. Serialization
        2. Using the Serializer Formatters
          1. Applying the Serializable Attribute
          2. Controlling Serialization Behavior
        3. Adding Serialization Support to Collection Classes
          1. The ArrayEx(T) Class
          2. The Linked List Classes
          3. The Associative Array Classes
            1. The AssociativeArrayAL(TKey,TValue) Class
            2. The AssociativeArrayHT Class
          4. The Queue Classes
          5. The Stack Classes
        4. Summary
    7. IV. Using Collections with UI Controls
      1. 10. Using Collections with Windows Form Controls
        1. Simple Binding
        2. Two-Way Data Binding
          1. Implementing the IBindingList Interface
            1. Adding List Manipulation Support
              1. AllowEdit
              2. AllowNew
              3. AllowRemove
              4. AddNew
            2. Adding Notification Support
            3. Adding Sorting Support
              1. SupportsSorting
              2. SortDirection
              3. SortProperty
              4. IsSorted
              5. ApplySort
              6. RemoveSort
            4. Adding Searching Support
              1. SupportsSearching
              2. Find
              3. AddIndex
              4. RemoveIndex
          2. Implementing the IBindingListView Interface
            1. Adding Filtering Support
              1. SupportsFiltering
              2. Filter
              3. RemoveFilter
            2. Adding Advanced Sorting
              1. SupportsAdvancedSorting
              2. SortDescriptions
              3. Modifications to IBindingList
              4. ApplySort
          3. Using the BindingList(T) Class
          4. Using the BindingSource Class
        3. Understanding the Sample Code
          1. Binding with the ComboBox Control
          2. Binding with the ListBox Control
          3. Binding with the DataGridView Control and IBindingList
          4. Binding with the DataGridView Control and IBindingListView
          5. Binding with the BindingSource Object
        4. Summary
      2. 11. Using Collections with WPF and Silverlight Controls
        1. INotifyCollectionChanged Overview
        2. Implementing the INotifyCollectionChanged Interface
          1. Notifying the User of Cleared Items
          2. Resolving Problems with the Recursive Collection Change Event
        3. ObservableCollection(T) Overview
        4. Using the ObservableCollection(T) Class
          1. Handling Recursive Collection Change Events
        5. ICollectionView and CollectionView Overview
          1. When to Use BindingListCollectionView
          2. When to Use ListCollectionView
        6. Understanding the Sample Code
          1. Binding with the ComboBox Control
          2. Binding with the ListBox Control
          3. Binding with the ListView Control
          4. Binding with the TreeView Control
          5. Binding with the CollectionView Class
        7. Summary
    8. A. About the Author
    9. Index
    10. About the Author
    11. Copyright