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
Дата добавления: 2015-09-18 | Просмотры: 516 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|