7. Collections || C# 10 Flashcards

1
Q

What the IEnumerator interface do?

A

Defines the basic low-level protocol by which elements in a collection are traversed in a forward-only manner
~~~
public interface IEnumerator{
bool MoveNext();
object Current {get; }
void Reset();
}
~~~
It also inherits from IDisposable which ensure that resources are released once the enumeration is completed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When would you implement IEnumerable<T> interface?</T>

A
  1. To support the foreach statement
  2. To interoperate with anything expecting a standard collection
  3. To meet the requirements of a more sophisticated collection interface
  4. To support collection initializers
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

To implement IEnumerable/IEnumerable<T> you must provide an enumerator. How would you do that?

A

You can do it in one of 3 ways:
1. If the class is “wrapping” another collection, by returning the wrapped collection’s enumerator
2. Via an iterator using yield return
3. By instantiating your own IEnumerator/IEnumerator<T> implementation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can you name at least 5 types that resides under Sysyem.Collection.Generic?

A
  1. Dictionary<TKey,TValue>
  2. HashSet<T>
  3. List<T>
  4. LinkedList<T>
  5. SortedDictionary<TKey,TValue>
  6. SortedList<TKey,TValue>
  7. SortedSet<T>
  8. Stack<T>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is ICollection<T> and ICollection? How does the methods differ between them?

A

ICollection<T> is the standart interface for countable collections of objects. It provides the ability to determine the size of a collection (Count), copy the collection into an array (ToArray) and determine whether the collection is read-only (IsReadOnly). Since it extends IEnumerable<T> it can also be traversed via foreach.
For writable collection you can also use Add, Remove and Clear methods

ICollection is nongeneric interface which is simillar in providing a countable collection, but it doesnt provide functionality for altering the list or checking for element membership:
Has only 1 method - CopyTo ant 3 parameters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How would you define IList<T> type?

A

IList<T> is the standart interface for collections indexable by position. In addition to the functionality inherited from ICollection<T> and IEnumerable<T> it provides the ability to read or write an element by position (via indexer) and insert/remove by position.
Nongerenic IList has more methods than IList<T> because it inherits less from ICollection

IList<T>:
int IndexOf(T item)
void Insert (int index, T item)
void RemoveAt (int index)

IList:
bool IsFixedSize {get; }
bool IsReadOnly {get; }
int Add (object value)
void Clear ()
bool Contains (object value)
int IndexOf (object value)
void Insert (int index, object value)
void Remove (object value)
void RemoveAt (int index)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why do we need IReadOnlyColletion<T> and IReadOnlyList<T> ?

A

This collection and list interfaces are designed for exposing the members required for read-only operations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the differences between an array and List?

A

Size: An array has a fixed size, meaning its size cannot be changed once it has been created. A List, on the other hand, has a dynamic size and can grow or shrink as needed.

Type: An array must be of a single data type, while a List can hold elements of any object type.

Indexing: Both arrays and Lists allow you to access elements using an index, but a List provides additional methods for inserting, removing, and searching elements.

Performance: Arrays have faster index-based access than Lists. However, Lists are generally faster for inserting and removing elements, especially in the middle of the collection.

Syntax: The syntax for working with arrays and Lists is slightly different, with Lists providing a more user-friendly and convenient API for common collection operations.

In general, if you need a collection of elements with a fixed size and a specific data type, use an array. If you need a dynamic-size collection that can hold elements of any type, use a List.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the differences between these array methods: Clone() and CopyTo() ?

A

The Clone() and CopyTo() methods in C# are both used to copy arrays, but they have some key differences:

Clone(): The Clone() method creates a shallow copy of the original array, meaning that a new array is created with the same elements as the original, but the elements themselves are not copied. Instead, the new array holds references to the same elements as the original. This means that changes to the elements in the new array will affect the elements in the original array.

CopyTo(): The CopyTo() method creates a shallow or deep copy of an array, depending on the type of elements in the array. If the elements are value types, a deep copy of the elements is made, meaning that changes to the elements in the new array will not affect the elements in the original array. If the elements are reference types, a shallow copy of the elements is made, meaning that changes to the elements in the new array will affect the elements in the original array.

In general, if you need to make a new array with independent elements, use CopyTo() with value types. If you need to create a new array that shares elements with the original array, use Clone() or CopyTo() with reference types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does the array method Resize() work?

A

Changes the number of elements of a one-dimensional array to the specified new size
public void Resize<T> (ref T[]? array, int newSize);
The Resize method works by creating a new array and copying over the elements, returning the new array via the reference parameter. Any references to the original array in other objects will remain unchanged.</T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Let’s say we have a List and ArrayList with value type elements inside. Which is faster? Why?

A

List<T> will be faster with value type elements because List<T> (if T is value type) avoids the overhead of boxing and unboxing elements

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a LinkedList<T>? What does it implement?

A

LinkedList<T> is a generic doubly linked list. A doubly linked list is a chain of nodes in which each references the node before, the node after and the actual element. Its main benefit is that an element can always be inserted efficiently anywhere in the list, because it just involves creating a new node and updating a few references, but the task of finding the place where to insert the node can be slow, because there is no indexing in linkedList; each node must be traversed
LinkedList<T> implements IEnumerable<T> and ICollection<T>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What does ‘concurrent’ mean?

A

The term “concurrent” refers to the ability of multiple processes or threads to execute simultaneously, either interleaved on a single processor or running on multiple processors. In computer science, “concurrent” is often used to describe operations that can run at the same time, independently, and without affecting each other’s results.

In the context of data structures, “concurrent modification” refers to the ability to modify the structure (e.g., add or remove elements) while it is being used or enumerated by another process or thread. A data structure that supports concurrent modification is designed to be safe to modify even while it is being used by other processes or threads, without causing errors or inconsistent results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is Queue? What are the main methods?

A

Queue is a First-In-First-Out (FIFO) data structure;
Main methods:
1. Enqueue (add element to the tail(end) if queue)
2. Dequeue (reveal and remove an element from the head(start) of the queue
3. Peek (reveal an element at the head, without removing it)

Queue does not implement IList interface since we can’t access items directly by indexes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a Stack? What is the main methods?

A

Stack is a Last-In First-Out data structure.
1. Push (add element at the top of the stack)
2. Pop (Reveal and remove an element at the top of the stack)
3. Peek (reveal an element at the top of the stack without removing it

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is a BitArray?

A

A BitArray is a dynamically sized collection of compacted bool values. It is more memory efficient than simple array of bool and a generic List of bool because it uses only one bit for each value, whereas the bool type in both other collections require one byte per each value

17
Q

What is a HashSet and SortedSet? What are the differences?

A

Both have distinguish features:
- Their Contains() method execute quickly using hash-based lookup;
- They do not store duplicate elements and silently ignore requests to add duplicates;
- You cannot access an element by position

Differences:
- SortedSet keeps elements in order whereas HashSet does not;
- HashSet is implemented with a hashtable that stores just keys SortedSet is implemented with red/black tree;

Both collections implement ICollection and offer methods Contains, Add and Remove

18
Q

What is a Dictionary? How does it work?

A

Dictionary is a collection in which each element is a key/value pair. Dictionaries are most commonly used for lookups and sorted lists.
To add an item to a dictionary, you either call Add or use the index’s set accessor - the latter adds an item to the dictionary if the key is not already present (or updates the item if it is present). Duplicate keys are forbidden in all dictionary implementations, so calling Add twice with the same key throws an exception
The original order in which the items where added is not retained. Items are not sorted. You cannot access items by index

19
Q

What are the dictionary classes? How do they differ?

A

Each dictionary class differ in the following regard:
- Whether items are stored in sorted sequence (SortedDictionary, SortedList)
- Whether items can be accessed by position (index) as well as by key (OrderedDictionary, SortedList)
- Whether generic or nongeneric
- Whether it’s fast or slow to retrieve items by key from a large dictionary (slowest: ListDictionary, fastest: Dictionary)

20
Q

How would you grade dictionary classes by Big-O notation?

A

O(1) (Great) : HashTable, Dictionary, OrderedDictionary

O(log n) (Meh) : SortedDictionary, SortedList
O(n) (BAD): ListDictionary, List (non dictionary type)

21
Q

What is an OrderedDictionary?

A

An OrderedDictionary is a nongeneric dictionary that maintains the elements in the same order that they were added. With an OrderedDictionary you can access elements both by key and by index.
An OrderedDictionary is a combination of a HashTable and an ArrayList. This means that it has all the functionality of a HashTable, plus functions such as RemoveAt and an integer indexer. It also exposes keys and values properties that return elements in their original order.

22
Q

What is a HybridDictionary?

A

Its a ListDictionary that automatically converts to HashTable upon reaching a certain size, to address ListDictionary’s with performance

23
Q

What is a red/black tree?

A

A data structure designed to perform consistently well in any insertion or retrieval scenario

24
Q

Compare SortedList<,> and SortedDictionary<,>

A

SortedDictionary is much faster than SortedList at inserting elements in a random sequence (particularly with large lists). SortedList however has an extra ability to access items by index as well as by key. With sorted list you can go directly to the nth element in the sorting sequence, but to do the same with SortedDictionary you must manually enumerate over n elements

25
Q

What is a KeyedCollection?

A

It subclasses Collection<TItem>. It both adds and subtracts functionality. What it adds is the ability to access items by key, much like with dictionary. What it subtracts is the ability to proxy your own inner list. It doesn’t support the concept of key/value pairs. It is like Collection<TItem> + fast lookup by key

26
Q

What is a ReadOnlyCollection<T>?

A

Is a wrapper or proxy that provides a read-only view of a collection. This is useful in allowing a class to publicly expose a read-only access to a collection that the class can still update internally. A read-only collection accepts the input collection in its constructor to which it maintains a permanent reference. It doesn’t take a static copy of the input collection, so subsequent changes to the input collection are visible through the read-only wrapper

27
Q

How the manipulation in immutable collections work?

A

The Add() method in immutable collection returns a new collection containing the existing elements plus the new one.
Remove() method works in the same way - returning a new collection without the element we just removed.
If we want to add or remove more than one element at a time we should use AddRange()/RemoveRange() which accepts IEnumerable<T> of items

28
Q

What is a Builder in collections? When do we use them?

A

Builders are classes that are functionally equivalent to a mutable collection, with similar performance characteristics.
We need builder for more complex initialisation - each immutable collection class defines a builder counterpart.

ImmutableArray<int>.Builder builder = ImmutableArray.CreateBuilder<int>();
builder.Add(1);
builder.Add(2);
builder.RemoveAt(0);
ImmutableArray<int> myImmutable = builder.ToImmutable();

We can also turn immutable array to builder using .ToBuilder(), then to immutable array - ToImmutable();

29
Q

What types can be used as keys in a Dictionary or Hashtable?

Don’t say a specific type

A

A type for which Equals and GetHashCode returns meaningful results

30
Q

What types can be used as a key in any of the sorted dictionaries or lists?

Don’t say a specific type

A

A type that implements IComparable / IComparable<T>

31
Q

What does a “plug-in” protocol do?
Which interfaces do they implement?

A
  1. They allow you to switch in alternative equating or comparison behaviour
  2. They allow you to use a dictionary or sorted collection with a key type that’s not intrisically equatable or comparable

Plug-in protocols consist of these protocols:
* IEqualityComparer and IEqualityComparer<T> :
1.1 Performs plug-in equality comparison and hashing
1.2 Recognized by Hastable and Dictionary
* IComparer and IComparer<T> :
2.1 Performs plug-in order comparison
2.2 Recognised by the sorted dictionaries and collections; also, Array.Sort

32
Q

If we look at the requirements of hashtable-based dictionaries, they need to aswer two questions. What are they?

A
  1. Is the given key is the as another key?
  2. What is the hashcode of this key’s integer?
33
Q

How do we implement IEqualityComparer<T>?

A

By overriding two abstract methods : Equals() and GetHashCode()

34
Q

Why is there a EqualityComparer<T>.Default when we have Equals() method? What it does?

A

Calling EqualityComparer<T>.Default returns a general-purpose equality comparer that you can use as an alternative to the static object.Equals method. The advantage is that it first checks whether T implements IEquatable<T>, and if so, it calls that implementation instead, avoiding the boxing overhead. This is particularly useful in generic methods:
~~~
static bool Foo<T> (T x, T y)
{
bool same = EqualityComparer<T>.Default.Equals (x, y);
...
}
~~~</T></T>

35
Q

When should we use IComparer/Comparer and when IEqualityComparer/EqualityComparer?

A

IComparer : sorted dictionaries and collections
IEqualityComparers : unsorted dictionaries such as Dictionary and Hashtable

36
Q

What is a StringComparer?

A

StringComparer is a predefined pug-in class for equating and comparing strings, allowing you to specify language and case sensitivity. StringComparer implements both IEqualityComparer and IComparer (and their generic versions), so you can use it with any type of dictionary or sorted collection.

Because StringComparer is abstract, you obtain instances via its static properties

37
Q

You have an array of names
string[] names = { "Tom", "HARRY", "sheila" }. How will you sort it using Australian culture?

A
string[] names = { "Tom", "HARRY", "sheila" };
CultureInfo ci = new CultureInfo ("en-AU");
Array.Sort<string> (names, StringComparer.Create(ci, false));

in Create() method, first we pass cultureInfo, and then “ignore case” boolean