Студопедия

Главная страница Случайная страница

КАТЕГОРИИ:

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Program that add element to LIST






using System.Collections.Generic; class Program{static void Main() { List < int> list = new List< int> (); list.Add(2); list.Add(3); list.Add(5); list.Add(7); }}

55. Queues in C#.

A queue is a collection where elements are processed first in, first out (FIFO). The item that is put first in the queue is read first. Examples of queues are standing in the queue at the airport, a human resources

queue to process employee applicants, print jobs waiting to be processed in a print queue, and a thread waiting for the CPU in a round - robin fashion. Often, there are queues where the elements processed

differ in their priority. For example, in the queue at the airport, business passengers are processed before economy passengers. Here, multiple queues can be used, one queue for every priority. At the airport this

can easily be found out, because there are separate check - in queues for business and economy passengers. The same is true for print queues and threads. You can have an array or a list of queues where one item

in the array stands for a priority. Within every array item there ’ s a queue, where processing happens with the FIFO principle.

A queue is implemented with the Queue < T > class in the namespace System.Collections.Generic. Internally, the Queue < T > class is using an array of type T, similar to the List < T > type. It implements the interfaces IEnumerable < T > and ICollection, but not ICollection < T >. ICollection < T > is not implemented because this interface defines Add() and Remove() methods which should not be available for queues.

The Queue < T > class does not implement the interface IList < T >, so you cannot access the queue using an indexer. The queue just allows you to add an item to the queue, where the item is put at the end of the

queue (with the Enqueue() method), and to get items from the head of the queue (with the Dequeue() method).

56. Stacks in C#.

A stack is another container that is very similar to the queue. You just use different methods to access the stack. The item that is added last to the stack is read first. The stack is a last in, first out (LIFO) container.

The Stack< T> class implements the interfaces IEnumerable< T> and ICollection.

Members Description
Count The property Count returns the number of items in the stack.  
Push() The Push() method adds an item on top of the stack.  
Pop() The Pop() method removes and returns an item from the top of the stack. If the stack is empty, an exception of type InvalidOperationException is thrown.  
Peek() The Peek() method returns an item from the top of the stack but does not remove the item.  
Contains() The Contains() method checks whether an item is in the stack and returns true if it is

 

.

57. Linked lists in C#.

LinkedList< T> is a doubly linked list, where one element references the next and the previous one.

Advantage of a linked list is that if items are inserted in the middle of a list, the linked list is very fast. When an item is inserted, only the Next reference of the previous item and the Previous reference of thenext item must be changed to reference the inserted item. With the List< T> class, when an element is inserted all following elements must be moved.

Disadvantage with linked lists. Items of linked lists can be accessed onlyone after the other. It takes a long time to find an item that’s somewhere in the middle or at the end ofthe list.A linked list cannot just store the items inside the list; together with every item, the linked list must haveinformation about the next and previous items.

The LinkedList< T> class itself defines members to access the first (First) and last (Last) item of the list, to insert items at specific positions (AddAfter(), AddBefore(), AddFirst(), AddLast()), to remove items

from specific positions (Remove(), RemoveFirst(), RemoveLast()), and to find elements where the search either starts from the begin (Find()) or the end (FindLast()) of the list.

 

 

58. Sorted lists in C#.

If the collection you need should be sorted based on a key, you can use SortedList < TKey, TValue >. This class sorts the elements based on a key. Not only can you use any type for the value, but also for the key. The example creates a sorted list where both the key and the value are of type string. The default constructor creates an empty list, and then two books are added with the Add() method. With overloaded constructors, you can define the capacity of the list and also pass an object that implements the interface IComparer < TKey >, which is used to sort the elements in the list. The first parameter of the Add() method is the key (the book title); the second parameter is the value (the

ISBN number). Instead of using the Add() method, you can use the indexer to add elements to the list. The indexer requires the key as index parameter. If a key already exists, the Add() method throws an

exception of type ArgumentException. If the same key is used with the indexer, the new value replaces the old value. SortedList < TKey, TValue > allows only one value per key. If you need multiple values

per key you can use Lookup < TKey, TElement >.

You can also access the values and keys by using the Values and Keys properties.

 

 

59. Dictionaries in C#.

Dictionaries represent a sophisticated data structure that allows you to access an element based on a key. In other words, A Dictionary class represents a dictionary in C# that is used to represent a collection of keys and values pair of data. This article demonstrates how to use a dictionary in C#.. Dictionaries are also known as hash tables or maps. The main feature of dictionaries is fast lookup based on keys. You can also add and remove items freely, a bit like a List< T>, but without the performance overhead of having to shift subsequent items in memory.

 

A good performance of the dictionary is based on a good implementation of the method GetHashCode().

 

SortedDictionary < TKey, TValue > is a binary search tree where the items are sorted based on the key. The key type must implement the interface IComparable < TKey >. If the key type is not sortable, you can also create a comparer implementing IComparer < TKey > and assign the comparer as a constructor argument of the sorted dictionary.

TKey - The type of the keys in the dictionary.

TValue - The type of the values in the dictionary.

 

using System; using System.Collections.Generic; class Program{ static void Main() { Example e = new Example(); Console.WriteLine(e.GetValue()); }} class Example{ Dictionary< int, int> _d = new Dictionary< int, int> () { {1, 1}, {2, 3}, {3, 5}, {6, 10} }; public int GetValue() { return _d[2]; // Example only } }Output: 3

60. Sets in C#.

A collection that contains only distinct items is known by the term set..NET 4 includes two sets, HashSet< T> and SortedSet< T>, that both implement the interface ISet< T>. HashSet< T> contains an unordered

list of distinct items; with SortedSet< T> the list is ordered. The ISet< T> interface offers methods to create a union of multiple sets, an intersection of sets, or give information if one set is a super- or subset of another.

With the sample code, three new sets of type string are created and filled with Formula-1 cars. The HashSet< T> class implements the ICollection< T> interface. However, the Add() method is implemented

explicitly and a different Add() method is offered by the class as you can see here. The Add() method differsby the return type; a Boolean value is returned to give the information if the element was added. If the elementwas already in the set, it is not added, and false is returned:

 

var companyTeams = new HashSet< string> ()

{ " Ferrari", " McLaren", " Toyota", " BMW", " Renault" };

var traditionalTeams = new HashSet< string> ()

{ " Ferrari", " McLaren" };

var privateTeams = new HashSet< string> ()

{ " Red Bull", " Toro Rosso", " Force India", " Brawn GP" };

if (privateTeams.Add(" Williams"))

Console.WriteLine(" Williams added");

if (! companyTeams.Add(" McLaren"))

Console.WriteLine(" McLaren was already in this set");

The result of these two Add() methods is written to the console:

Williams added

McLaren was already in this set

 

 


Поделиться с друзьями:

mylektsii.su - Мои Лекции - 2015-2024 год. (0.012 сек.)Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав Пожаловаться на материал