c# arrays and collections

Keywords: C# .NET


The content of this article comes from the open source e-book WoW C#, which I wrote. It is now being written. You can go to Wow CSharp / learning path summary. md at master · sogeisetsu / wow CSharp (GitHub. Com) To see the progress of writing. It is expected that the compilation will be completed by the end of 2021, and all proofreading and conversion of e-books will be completed before February 2022, so as to strive to put the book on Amazon's shelves in 2022. The purpose of writing this book is because the current. NET market is relatively depressed. Many excellent books are written based on the. NET framework framework, which is too different from the current. NET 6. The formal. NET 5 learning tutorial now almost only has MSDN, but MSDN is accurate and beautiful, but it is too trivial. Students who have not read the development documents are easy to be confused, so, I wrote WoW C#, which is based on. NET 5. My level is limited. Welcome to the open source warehouse of this book sogeisetsu/WOW-Csharp Attention, criticism, suggestions and guidance.

The concept of array and set

Array is an object with specified length and data type, which has some limitations in practical application.

The set is born for this limitation. The length of the set can be changed as needed, and it is also allowed to store values of any data type.

Array,ArrayList and List<T>

Array, ArrayList and List are all derived from IList, and they all implement the IEnumerable interface

In a sense, ArrayList and List belong to the category of collection, because they both come from the assembly System.Collections. However, they are data structures that store multiple variables, and they are not similar to the combination of key value pairs, and there is no first in first out or first in last out mechanism, so they are called arrays.

We generally call array. ArrayList and list < T > are arrays.

Array

Array must define the outermost length of the array when the assignment is defined and not initialized (except for declaring array variables without initialization). For example:

int[] vs = new int[10];
int[,] duoWei = new int[3, 4];
int[][] jiaoCuo = new int[3][]; // The array consists of three one-dimensional arrays

One dimensional array

definition

Define an array in a similar way

int[] array = new int[5];

Initialization assignment

Initialize in a manner similar to this

int[] array1 = new int[] { 1, 3, 5, 7, 9 };

Implicit initialization is also possible

int[] array2 = { 1, 3, 5, 7, 9 };
string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };

First declare and then assign values in a manner similar to the following

int[] array3;
array3 = new int[] { 1, 3, 5, 7, 9 };   // OK
//array3 = {1, 3, 5, 7, 9};   // Error

Multidimensional array

Arrays can have multiple dimensions. Each element of a multidimensional array is an element of the type to which the array belongs at the time of declaration. For example, every element of int [,] is of type int, not int []. In other words, multidimensional arrays cannot be regarded as "arrays composed of arrays".

definition

Declare the length of a two-dimensional array in a manner similar to the following

int[,] array = new int[4, 2];

Initialization assignment

Initialize the multidimensional array in a manner similar to the following:

// Two-dimensional array.
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// The same array with dimensions specified.
int[,] array2Da = new int[4, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
// A similar array with string elements.
string[,] array2Db = new string[3, 2] { { "one", "two" }, { "three", "four" },
                                        { "five", "six" } };

// Three-dimensional array.
int[,,] array3D = new int[,,] { { { 1, 2, 3 }, { 4, 5, 6 } },
                                 { { 7, 8, 9 }, { 10, 11, 12 } } };

You can also initialize an array without specifying a level

int[,] array4 = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };

Declare array variables without initialization:

int[,] array5;
array5 = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };   // OK
//array5 = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

Element assignment and get element

You can get the value of the array and assign a value to the array in a way similar to array[1,2].

GetLength(0) can obtain the length of the outermost array, and GetLength(1) can obtain the length of the second layer array. and so on. The way to assign values to a two-dimensional array duoWei loop is as follows:

Console.WriteLine("Two dimensional array assignment");
for (int i = 0; i < duoWei.GetLength(0); i++)
{
    for (int j = 0; j < duoWei.GetLength(1); j++)
    {
        duoWei[i, j] = i + j;
    }
}

How to get the number of elements in a two-dimensional array?

int[,] array = new int[,] {{1,2,3},{4,5,6},{7,8,9}};//Define a two-dimensional array with 3 rows and 3 columns
int row = array.Rank;//Gets the dimension, which refers to the number of rows
int col = array.GetLength(1);//Gets the number of elements in the specified dimension, which is the number of columns. (0 is the first dimension and 1 is the second dimension)
int col = array.GetUpperBound(0)+1;//Get the upper index limit of the specified dimension, and add a 1 to get the total number, which represents the number of rows of the two-dimensional array
int num = array.Length;//Gets the length of the entire two-dimensional array, that is, the number of all elements

Source: How to obtain the two-dimensional length of a two-dimensional array, that is, the number of rows and columns, in C #? And the length of each dimension of the multidimensional array- jack_Meng - blog Park (cnblogs.com)

Staggered array

An interleaved array is an array whose elements are arrays and may be of different sizes. Interleaved arrays are sometimes referred to as "arrays of arrays".

Staggered arrays are declared without initialization as follows:

int[][] ccf;
ccf = new int[3][];

Staggered array is similar to python's multidimensional array, which is more in line with human intuition. An staggered array contains multiple arrays.

definition

You can declare an interleaved array in a manner similar to the following:

// Defining a multi-dimensional array requires the same length of each dimension. The following defines an interleaved array
int[][] jiaoCuo = new int[3][]; // The array consists of three one-dimensional arrays

The array declared above is a one-dimensional array with three elements, each of which is a one-dimensional integer array.

An initialization expression can be used to populate array elements with values, in which case the array size is not required. For example:

jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };

Initialization assignment

You can initialize an array when it is declared, such as:

int[][] jaggedArray2 = new int[][]
{
new int[] { 1, 3, 5, 7, 9 },
new int[] { 0, 2, 4, 6 },
new int[] { 11, 22 }
};

Get element and single assignment

You can use a method similar to jiaoCuo[1][1] to obtain the value of a single element, or you can use a method similar to jiaoCuo[1][1] = 2; To assign a value to a single element.

Cyclic assignment can be performed in a manner similar to the following:

Console.WriteLine("Staggered array cyclic assignment");
// First declare the length of each array in the staggered array
for (int i = 0; i < 3; i++)
{
    jiaoCuo[i] = new int[i + 1];
}
// Each element in the interleaved array is then assigned a value
for (int i = 0; i < jiaoCuo.Length; i++)
{
    Console.WriteLine($"Interleaved array{i + 1}layer");
    for (int j = 0; j < jiaoCuo[i].Length; j++)
    {
        jiaoCuo[i][j] = i + j;
        Console.WriteLine(jiaoCuo[i][j]);
    }
}

Methods and properties

Like arrays, which store multiple variables, the most important data structures are adding, deleting, obtaining length and data type conversion. Because of the characteristics of Array, the length of Array cannot be changed, so adding, deleting and modifying can only be done.

change

The Array type is modified in a manner similar to the following:

vs[0] = 12; //One dimensional array
duoWei[1, 2] = 3; //Multidimensional array
jiaoCuo[1][1] = 2; //Staggered array

check

The Array type is queried in a manner similar to the following:

int[] vs = new int[10];
vs[0] = 12;
Console.WriteLine(Array.IndexOf(vs, 12)); //0
Console.WriteLine(vs.Contains(12)); // True

Get length

It can be obtained in a way similar to the following:

Console.WriteLine(vs.Length);
Console.WriteLine(vs.Count());

The Length of the interleaved array is to obtain the number of contained arrays, the Length of the multidimensional array is to obtain the total number of elements of the array, the multidimensional array GetLength(0) can obtain the Length of the outermost array, and GetLength(1) can obtain the Length of the second layer array. and so on.

Array.ConvertAll() data type conversion

Array. Convertall < tinput, toutput > (tinput [], converter < tinput, toutput >) can be used to convert array types.

The parameters are as follows:

  • array

    TInput[]

Zero based one-dimensional to convert to target type Array.

Used to convert each element from one type to another Converter.

Source: [Array.ConvertAll(TInput) ], Converter) method (System) | Microsoft Docs

The demo is as follows:

double[] vs3 = Array.ConvertAll(vs, item => (double)item);

section

By default, only one-dimensional arrays can be sliced, or one-dimensional arrays obtained by interleaving arrays can also be sliced.

The slicing method is similar to vs[1..5], indicating that the vs array is from 1 to 5, closed on the left and open on the right^ 1 means - 1, the last element. [^ 3.. ^ 1] indicates from the penultimate element to the penultimate element, closed on the left and open on the right.

Get single element and assignment

You can obtain a single element and assign a value to a single element separately in the following ways:

// One dimensional array
Console.WriteLine(vs[1]);
vs[1] = 2;
// Multidimensional array
Console.WriteLine(duoWei[1, 2]);
duoWei[1, 2] = 3;
// Staggered array
Console.WriteLine(jiaoCuo[1][0]);
jiaoCuo[1][0] = 0;

Array.ForEach loop

There is also a ForEach method in System.Array, which is used for array.

demo:

Array.ForEach(vs, item => Console.WriteLine(item));

ArrayList

definition

Declare ArrayList in any of three ways similar to the following:

ArrayList() initialization ArrayList Class, which is empty and has the default initial capacity.
ArrayList(ICollection) initialization ArrayList Class that contains elements copied from the specified collection and has the same initial capacity as the number of elements copied.
ArrayList(Int32) initialization ArrayList Class, which is empty and has the specified initial capacity.

Arraylist can be regarded as an array whose length can be freely transformed and can contain elements of different data types.

Initialization assignment

The assignment can be initialized in a manner similar to the following:

ArrayList arrayList1 = new ArrayList() { 12, 334, 3, true };

loop

Loops can use for and foreach.

foreach (var item in arrayList)
{
    Console.WriteLine(item);
}

Methods and properties

Similar to list < T > but without ConvertAll method. ArrayList itself does not have a foreach method, but you can also use the traditional foreach method (like the previously mentioned ArrayList loop).

Please check the specific methods and properties Methods and properties of the List section

List<T>

definition

Declare list < T > in any of the following three ways:

List() initialization List Class, which is empty and has the default initial capacity.
List(IEnumerable) initialization List Class that contains elements copied from the specified collection and has sufficient capacity to accommodate the copied elements.
List(Int32) initialization List Class, which is empty and has the specified initial capacity.

initialization

Initialize at declaration time in a manner similar to the following:

List<string> listA = new List<string>() { "hello", " ", "wrold" };

loop

List < T > has a method named ForEach:

public void ForEach (Action<T> action);

The essence of this method is to List For each element of the Action entrust. Action The parameter of is each element of list < T > during the loop.

The demo is as follows:

// statement
List<string> listA = new List<string>() { "hello", " ", "wrold" };
// loop
var i = 0;
listA.ForEach(item =>
              {
                  Console.WriteLine($"The first{i + 1}individual");
                  Console.WriteLine(item);
                  i++;
              });

It is parsed from obtaining length, adding query, deleting, data type conversion, slicing and loop. Except for the data type conversion and the ForEach method owned by the list < T > type itself, they are applicable to ArrayList.

First state a list < string > as the basis of the demonstration:

List<string> listA = new List<string>() { "hello", " ", "wrold" };

Attribute length

The Count property gets the length

Console.WriteLine(listA.Count);

Attribute value

Console.WriteLine(listA[0]);

increase

To Add an element, you can use the Add method:

listA.Add("12");

check

IndexOf gets the location and Contains gets whether it is included.

Console.WriteLine(listA.IndexOf("12"));
Console.WriteLine(listA.Contains("12"));

Delete

Remove deletes according to the data and RemoveAt deletes according to the location.

listA.Remove("12");
listA.RemoveAt(1);

change

You can use something similar to listA[1] = "change"; To modify the element content.

section

You can use GetRange(int index, int count) to slice. The first parameter is the starting position of the slice, and the second parameter is the number of slices, that is, several numbers from index.

Console.WriteLine(listA.GetRange(1, 1).Count);

loop

List < T > has a method named ForEach. The essence of this method is to List For each element of the Action entrust. Action The parameter of is each element of list < T > during the loop.

The demo is as follows:

// statement
List<string> listA = new List<string>() { "hello", " ", "wrold" };
// loop
var i = 0;
listA.ForEach(item =>
              {
                  Console.WriteLine($"The first{i + 1}individual");
                  Console.WriteLine(item);
                  i++;
              });

Data type conversion

ConvertAll can be used to convert the data type of the Array, which is the method of list < T >. There is also ConvertAll method in System.Array, which is used for Array.

List<object> listObject = listA.ConvertAll(s => (object)s);

difference

Member single type Variable length Slice friendly Rich methods Add query, delete and modify ConvertAll
One dimensional array Check and modify
Multidimensional array Check and modify
Staggered array Check and modify
ArrayList Add query, delete and modify
List<T> Add query, delete and modify

The biggest advantage of Array is that it is slicing friendly. It can be sliced in a way similar to [1.. 3], which is more intuitive than GetRange. The list < T > type can be converted to Array through the ToArray method.

Conversion between array, ArrayList and list < T >

Details of the demo code for this part can be found from Conversion between Array,ArrayList and List · sogeisetsu/Solution1@88f27d6 (github.com) get.

First declare the three data types separately.

// Declaration array
int[] a = new int[] { 1,3,4,5,656,-1 };
// Declare multidimensional array
int[,] aD = new int[,] { { 1, 2 }, { 3, 4 } };
// Declare interleaved arrays
int[][] aJ = new int[][] {
    new int[]{ 1,2,3},
    new int[]{ 1}
};
// Declare ArrayList
ArrayList b = new ArrayList() { 1, 2, 344, "233", true };
// Declaration list < T >
List<int> c = new List<int>();

Array to ArrayList

// Array to ArrayList
ArrayList aToArrayList = new ArrayList(a);

Array to list < T >

List<int> aToList = new List<int>(a);
List<int> aToLista = a.ToList();

List < T > to Array

int[] cToList = c.ToArray();

List < T > to ArrayList

ArrayList cToArrayList = new ArrayList(c);

ArrayList to Array

In the process of conversion, the accuracy of the data type will be lost. In short, the converted Array will become an object

// ArrayList to Array
object[] bToArray = b.ToArray();

This conversion is of little significance. If you force the Array.ConvertAll method to convert data types after conversion, errors such as Unable to cast object of type 'System.String' to type 'System.Int32' may occur. This is because the members of ArrayList itself can not be of a single type.

Array printing

Printing of Array

For Array printing, I found four methods, as follows:

  • Call Array.ForEach

    Array.ForEach(a, item => Console.WriteLine(item));
    
  • Traditional forEach

    foreach (var item in a)
    {
    Console.WriteLine(item);
    }
    
  • Traditional for

    for (int i = 0; i < a.Count(); i++)
    {
    Console.WriteLine(a[i]);
    }
    
  • string.Join

    Console.WriteLine(string.Join("\t", a));
    

Printing of ArrayList

All I know about the printing of ArrayList is the traditional for and foreach methods.

Print of list < T >

In addition to the traditional for and foreach printing methods, list < T > also has its own foreach:

var i = 0;
listA.ForEach(item =>
              {
                  Console.WriteLine($"The first{i + 1}individual");
                  Console.WriteLine(item);
                  i++;
              });

Please note: ArrayList and list < T > do not have string.Join and call Array.ForEach to print the array.

Key value pair set

The set of elements that can be accessed by keys is called the set of key value pairs. This is a noun created by the author. They belong to a part of the set. In many cases, what we call a set is a set of key value pairs. Each item in the key value pair set has a key / value pair. The key is used to access items in the collection.

HashTable

Represents a collection of key / value pairs organized according to the hash code of the key.

The Key and Value of Hashtable are both object types, so when using Value types, boxing and unpacking operations are bound to occur. So the performance will be weak.

Constructor

There are many constructors for HashTable. You can see the details Hashtable class (System.Collections) | Microsoft Docs

The most common are:

Hashtable Object name = new Hashtable ();

Key value pairs in Hashtable are of object type, so Hashtable can support any type of key value pairs, and any non null object can be used as a key

If NULL is used as a part of hashtable in the following way, an error of System.ArgumentNullException: "Key cannot be null. Arg_ParamName_Name" will be reported.

Hashtable hashtable = new Hashtable();
int? a = null;
hashtable.Add(a, "123");
Console.WriteLine(a);

Methods and properties

The properties and methods commonly used in the Hashtable class are shown in the following table.

Property or method effect
Count The actual number of elements stored in the collection
void Add(object key,object value) Add elements to the collection
void Remove(object key) Removes the corresponding collection element according to the specified key value
void Clear() Empty collection
ContainsKey (object key) Determines whether the collection contains elements with the specified key value
ContainsValue(object value) Determines whether the collection contains the element with the specified value

Value

Each element is a key / value pair stored in an object DictionaryEntry . The key cannot be null, but the value can be.

You can take values in a way similar to the collection name. [Key]. Each element of a HashTable is a DictionaryEntry class. This class has two attributes, Key and Value, which can obtain the Key and Value of each element. Because hashtables are arranged out of order, DictionaryEntry can only be obtained through foreach.

foreach (DictionaryEntry item in hashtable)
{

    Console.WriteLine(item);
    Console.WriteLine(item.Key);
    Console.WriteLine(item.Value);
    Console.WriteLine("-=-=-=-=-=-=-=-=-=");
}

The Hashtable class is not recommended for new development. Instead, we recommend using generics Dictionary Class. For details, see on GitHub Non generic collections should not be used .

Source: Hashtable class (System.Collections) | Microsoft Docs

SortedList

Represents a collection of key / value pairs that sort keys and are accessible by key and index.

SortedList has two types, one is System.Collections . SortedList, one is System.Collections.Generic.SortedList . The latter uses generics, has a single member type, is safer and has better performance.

The SortedList class is not recommended for new development. Instead, we recommend using generics System.Collections.Generic.SortedList Class. For details, see on GitHub Non generic collections should not be used .

Source: SortedList class (System.Collections) | Microsoft Docs

SortedList Object internally maintains two arrays for storing list elements; That is, one array is used to store keys and the other array is used to associate values. Each element is a key / value pair that can be accessed as an object DictionaryEntry . The key cannot be null, but the value can be.

The properties and methods used in the SortedList collection are similar to Hashtable, and will not be repeated here. Its characteristic is that it can be accessed by index.

Constructor

There are many constructors that you can view SortedList class (System.Collections) | Microsoft Docs . The most commonly used are:

SortedList sortedList = new SortedList();

Value

You can take values in a way similar to the collection name. [key], or you can use GetKey(Int32) To get build and use GetByIndex(Int32) To get the value. The order is the order in which the elements are added

for (int i = 0; i < sortedList.Count; i++)
{
    Console.WriteLine($"{sortedList.GetKey(i)}\t{sortedList.GetByIndex(i)}");
}

Dictionary

In the case of single thread, it is the fastest of all collection types. Dict for short.

It is essentially a generic class of HsashTable. Because the Key and Value of Hashtable are both object types, boxing and unpacking operations are bound to occur when using Value types. Therefore, the performance is certainly not as good as that of Dictionary. I won't make too many comparisons here.

As long as the object is used as a key in Dictionary , it must not be changed in any way that affects its hash value. According to the dictionary's equality comparator, each key in the Dictionary Must be unique. The key cannot be null, but if its type is reference type, the value can be TValue.

Construction method

The most common construction method is the following one. Please refer to others Dictionary class (System.Collections.Generic) | Microsoft Docs

Dictionary<int, string> dictionary = new Dictionary<int, string>();

Other methods, attributes and value methods are the same as HashTable. The only difference is that Dictionary Is a collection of keys and values, so the element type is not the type of key or value. Instead, the element type is KeyValuePair Key type and value type. Each element of a HashTable is a key / value pair that can be accessed as an object DictionaryEntry.

foreach (KeyValuePair<int, string> item in dictionary)
{
    Console.WriteLine($"{item.Key}\t{item.Value}\tover");
}

It is recommended to use Dictionary in single threaded programs, which has the advantage of generics, fast reading speed and full capacity utilization. Hashtable is recommended for multithreaded programs. The default hashtable allows single thread writing and multithreaded reading. Further calling the Synchronized() method on the hashtable can obtain a fully thread safe type. While Dictionary is not thread safe, it must be protected manually with lock statement, which greatly reduces the efficiency.

difference

Direct value method generic paradigm Characteristics (purpose) Element type
HashTable Key value pair nothing Key value pairs for multi-threaded storage DictionaryEntry
HashSet Unordered, no key value pair, unable to get value directly. have It is used to store non repeating elements and perform set operation efficiently. generic types
SortedList Key value pair, index nothing Used for requirements with sequential indexing. Sorteddictionary < tkey, tvalue > DictionaryEntry
Dictionary Key value pair have It is recommended to use Dictionary in single threaded programs, which has the advantage of generics, fast reading speed and full capacity utilization. KeyValuePair

Mutual conversion

I don't think the type conversion of a set is meaningful, because the meaning of a set is a reference type that stores data. At the beginning of program design, the type of collection has been determined through possible future use scenarios. Just as a class has an attribute of type int, it should not be converted to Double when used later.

Here we only talk about the conversion between HashTable and Dictionary.

For the conversion between non generic classes and generic classes, type safety must be considered at the beginning of the conversion, otherwise many errors may occur.

HashTable to Dict

// hashtable to Dict
Dictionary<int, int> dictionary = new Dictionary<int, int>();
foreach (DictionaryEntry item in hashtable)
{
    dictionary.Add((int)item.Key, (int)item.Value);
}

Dict to HashTable

// Dict to Hashtable
Hashtable hashtable1 = new Hashtable(dictionary);

Printing of sets

It is very convenient to print using traditional foreach. When printing, you need to consider the different types of collection elements. Although var can help us not to remember those annoying type names, sometimes the IDE can't make the code automatic reminder function work properly because of the use of var.

foreach (var item in dictionary)
{
    Console.WriteLine($"key:{item.Key}\tvalue:{item.Value}");
}

Generic collections are recommended

Microsoft officially recommends the use of generic collections. Because non generic collections have the problems of Error prone and less performer, Microsoft provides classes to replace non generic collections. The excerpt is as follows:

Type Replacement
ArrayList List
CaseInsensitiveComparer StringComparer.OrdinalIgnoreCase
CaseInsensitiveHashCodeProvider StringComparer.OrdinalIgnoreCase
CollectionBase Collection
Comparer Comparer
DictionaryBase Dictionary or KeyedCollection
DictionaryEntry KeyValuePair
Hashtable Dictionary
Queue Queue
ReadOnlyCollectionBase ReadOnlyCollection
SortedList SortedList
Stack Stack

Source: platform-compat/DE0006.md at master · dotnet/platform-compat (github.com)

HashSet<T>

HashSet is an optimized unordered set that provides high-speed element lookup and high-performance set set operations. Moreover, HashSet was introduced in. NET 3.5 under the System.Collection.Generic namespace.

HashSet allows elements to be null as long as generic classes allow nulls.

HashSet will automatically remove duplicate values during the process of adding elements, and no error will be reported.

HashSet Class provides high-performance setting operations. A set is a set that does not contain duplicate elements, and its elements have no specific order.

Some features of HashSet are as follows:

​ a. Values in a HashSet cannot be repeated and have no order.

​ b. The capacity of the HashSet is automatically added as needed.

HashSet is not a collection of key value pairs.

HashSet can only contain unique elements, and its internal structure has been specially optimized for this. It is worth noting that HashSet can also store a single null value. We can draw a conclusion: if you want to have a set with unique value, HashSet is your best choice, and it also has ultra-high retrieval performance.

Constructor

The more common constructors are as follows. For more constructors, see HashSet class (System.Collections.Generic) | Microsoft Docs.

HashSet<int> hashSet = new HashSet<int>();

Methods and properties

Please check the specific methods and properties HashSet class (System.Collections.Generic) | Microsoft Docs.

Common methods and attributes such as clear, remove, add and count will not be repeated.

set operation of HashSet

HashSet class is mainly designed for high-performance set operations, such as intersection, union, difference, etc. of two sets.

To facilitate understanding, draw a diagram first. A and B are two light blue circles, and C is the intersection of a and B. The contents of this figure will be used later.

Define two hashsets named setA and setB, representing A and B in the figure respectively.

IsProperSubsetOf proper subset

determine HashSet Object is a true subset of the specified collection.

// Determines whether setA is a true subset of setB
Console.WriteLine(setA.IsProperSubsetOf(setB)); // True
Console.WriteLine(setC.IsProperSubsetOf(setB)); // False

Union with union

Modify current HashSet Object to contain all elements that exist in the object, in the specified collection, or both. In fact, it is to modify the current set to the union of two sets. Find A+B in the graph.

// Find the union of two
setA.UnionWith(setB);
// Now setA is the union of two sets
foreach (var item in setA)
{
    Console.WriteLine(item);
}

IntersectWith intersection

Change the current set into the intersection of two sets and find C in the graph.

// Find intersection
setA.IntersectWith(setB);
// Now setA is the intersection of two
foreach (var item in setA)
{
    Console.WriteLine(item);
}

ExceptWith difference set

Removes the intersection and removes all elements in the specified set from the current HashSet object. In essence, it is to find A-C in the graph.

// Remove the intersection and remove all elements in the specified set from the current HashSet < T > object.
setA.ExceptWith(setB);
foreach (var item in setA)
{
    Console.WriteLine(item);
}

SymmetricExceptWith

Contains only elements (but not both) that exist in the object or in the specified collection. It is essentially (A-C)+(B-C).

//Contains only elements (but not both) that exist in the object or in the specified collection.
setA.SymmetricExceptWith(setB);
foreach (var item in setA)
{
    Console.WriteLine(item);
}

Jason analysis

json is a format similar to storing data through key value pairs. When operating the database, class data is usually converted to json format, then stored in the database, and then converted to class instantiation objects when used. A complete set of solutions of the spring boot framework of java can complete this operation through mybatis and fastjson. In the front and back-end data transmission of the web, json is generally used as the data carrier, and JavaScript has relatively complete support for json.

Json format overview

  • Basics

    1. Concept: Javascript object notation
    • json is now mostly used to store and exchange text information

    • Data transmission

    • JSON is smaller, faster, and easier to parse than XML.

    1. Syntax:

    2. Basic rules

    -  Data in name/Value alignment: json Data consists of key value pairs
    
    -  Key Quotes(Either one or both)Quotation marks can also be omitted
    
    -  Value type:
    
      1. Number (integer or floating point number)
    
      2. String (in double quotes)
    
      3. Logical value( true or false)
    
      4. Array (in square brackets)	{"persons":[{},{}]}
    
      5. Object (in curly braces) {"address":{"province": "Shaanxi"....}}
    
      6. null
    
    -  Data is separated by commas: multiple key value pairs are separated by commas
    
    -  Saving objects with curly braces: Using{}definition json format
    
    -  Save array in square brackets:[]
    
    1. JavaScript get data:
  1. json object. Key name

  2. json object ["key name"]

  3. Array object [index]

  4. ergodic

analysis

Serialization and deserialization of JSON using C # -. NET | Microsoft Docs

Two nouns are used, serialization and deserialization. Serialization refers to converting an instance object into a string in json format, and deserialization is the process of reverse serialization.

During serialization, only public read-write properties are serialized by default. Public fields can be included through the JsonInclude property of System.Text.Json.Serialization or the IncludeFields property of JsonSerializerOptions. Non public property accessors that can be serialized can be customized through the JsonInclude property of System.Text.Json.Serialization (that is, the access modifier of the attribute is public, but either set accessor or get accessor is non-public) . this may not be suitable for people who are used to java. In fact, it is a very reasonable serialization requirement. By default, the serializer will serialize all readable attributes in the object and deserialize all writable attributes. This way respects the role of access modifiers. You can also serialize non-public attributes with the open source newtonsoft.jason. Many programming languages now use it (including. NET) it is unreasonable to obtain private properties through reflection. It is obvious from the. NET core that the. NET team is restricting the use of reflection for security reasons.

Required namespace:

using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
  • The JsonSerializer.Serialize method of System.Text.Json can be used for serialization.
  • Use the JsonSerializer.Deserialize method of System.Text.Json to deserialize.
  • Use System.Text.Json.Serialization to add necessary features to the class to be serialized, such as JsonPropertyName renaming when serializing properties, and JsonInclude to define the fields to be included during serialization.
  • Use System.Text.Encodings.Web and System.Text.Unicode to enable a specific character set to be serialized normally during serialization instead of being escaped to \ uxxxx, where xxxx is the Unicode code of the character. In fact, by default, the serializer will escape all non ASCII characters.

serialize

Only the instantiated object is transformed into json string. Suppose there is an instantiated object weatherForecast. The serialization method is as follows:

string jsonString = JsonSerializer.Serialize(weatherForecast);

Deserialization

It refers to serializing json strings into instantiated objects, which is followed by the above, as follows:

weatherForecast = JsonSerializer.Deserialize<WeatherForecastWithPOCOs>(jsonString);

JsonSerializerOptions

Information such as whether to print neatly and ignore Null value properties can be specified through JsonSerializerOptions. The method is to instantiate JsonSerializerOptions and then treat them as parameters of JsonSerializer.Serialize and JsonSerializer.Deserialize.

You can view the properties of JsonSerializerOptions How to use System.Text.Json to instantiate JsonSerializerOptions | Microsoft Docs

First instantiate a JsonSerializerOptions object and define various properties in the initializer:

JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
    // Neat printing
    WriteIndented = true,
    // Ignoring property with Null value
    IgnoreNullValues = true,
    // Sets the encoding supported by the Json string. By default, the serializer will escape all non ASCII characters. That is, they will be replaced with \ uxxxx, where xxxx is the Unicode of the character
    // Code. The generated josn string can be serialized without escaping the specified character set by setting Encoder. The following specifies the basic Unicode block of the Basic Latin letter and the unified ideograph of China, Japan and South Korea
    // (U+4E00-U+9FCC). It basically covers the languages of all western countries except Cyrillic letters and the languages of China, Japan, South Korea and Vietnam in Asia
    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs),
    // Deserialization is not case sensitive
    PropertyNameCaseInsensitive = true,
    // Hump naming
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,

    // Hump naming of dictionary keys
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
    // null value attribute is ignored when serializing
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    // The read-only attribute is ignored. Because the read-only attribute can only be serialized and cannot be deserialized, serializing the read-only attribute is of little significance when json is used as the medium for storing data
    IgnoreReadOnlyFields = true,
    // Nonstandard json with comma at the end is not allowed
    AllowTrailingCommas = false,
    // Nonstandard json with comments is not allowed
    ReadCommentHandling = JsonCommentHandling.Disallow,
    // Allows strings that should have been numbers (numbers with quotes) to be converted to numbers during deserialization
    NumberHandling = JsonNumberHandling.AllowReadingFromString,
    // Handle circular reference types. For example, there is an attribute in the Book class, which is also the Book class
    ReferenceHandler = ReferenceHandler.Preserve
};

Then, during serialization and deserialization, the jsonSerializerOptions object is passed as a parameter to JsonSerializer.Serialize and JsonSerializer.Deserialize:

string jsonBookA = JsonSerializer.Serialize(bookA, jsonSerializerOptions);
// Deserialization
BookA bookA1 = JsonSerializer.Deserialize<BookA>(jsonBookA, jsonSerializerOptions);

Overview of common properties of JsonSerializerOptions

effect Value type
WriteIndented Print neatly. When this value is set to true, the serialized json string will be indented and wrapped automatically during printing. The default is false. bool
IgnoreNullValues Property with Null value is ignored. The default is false. bool
Encoder Set the encoding supported by the Json string. By default, the serializer will escape all non ASCII characters. That is, they are replaced with \ uxxxx, where xxxx is the Unicode code of the character. The generated josn string can be serialized without escaping the specified character set by setting Encoder. It can be set to Encoder = javascriptencoder.create (Unicode ranges. Basiclatin, Unicode ranges. Cjkunifiedideograms) to contain all western countries except Cyrillic letters and Asian Chinese, Japanese, Korean and Vietnamese characters JavaScriptEncoder
PropertyNameCaseInsensitive Deserialization is case insensitive. The default is false. bool
PropertyNamingPolicy The naming method of attributes during serialization is commonly used to name the hump with JsonNamingPolicy.CamelCase set to start with lowercase letters. JsonNamingPolicy
DictionaryKeyPolicy When serializing, the string key of the dictionary is named with a hump beginning with a lowercase letter. JsonNamingPolicy
DefaultIgnoreCondition Specifies a condition that determines when attributes with default values are ignored during serialization or deserialization. The default value is Never . The common value is JsonIgnoreCondition.WhenWritingDefault to ignore the default value attribute. JsonIgnoreCondition
IgnoreReadOnlyFields The read-only attribute is ignored when serializing. Because the read-only attribute can only be serialized and cannot be deserialized, serializing the read-only attribute is of little significance when json is used as the medium for storing data. The default is false. bool
AllowTrailingCommas During deserialization, nonstandard json with comma at the end is allowed, and the default is false. bool
ReadCommentHandling During deserialization, nonstandard json with comments is allowed, and the default is false. bool
NumberHandling Use NumberHandling = JsonNumberHandling.AllowReadingFromString to allow strings that should have been numbers (numbers with quotes) to be converted to numbers during deserialization JsonNumberHandling
ReferenceHandler Configure how object references are handled when reading and writing JSON. Using ReferenceHandler = ReferenceHandler.Preserve will still retain references and handle circular references during serialization and deserialization. ReferenceHandler
IncludeFields Determines whether fields are processed during serialization and deserialization. The default value is false. bool

System.Text.Json.Serialization attribute

You can add attributes to the properties and fields of the class that will be serialized and deserialized.

JsonInclude contains specific public fields and non-public property accessors

When serializing or deserializing, use JsonSerializerOptions.IncludeFields Global settings or[ JsonInclude] Attribute to contain a field (must be public). When applied to a property, it indicates that non-public getter s and setter s can be used for serialization and deserialization. Non-public properties are not supported.

demo:

/// <summary>
///Time stamp
/// </summary>
[JsonInclude]
public long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();

/// <summary>
///Title of the book
/// </summary>
[JsonInclude]
public string Name { private get; set; } = "<Title";

JsonPropertyName custom property name

To set the name of a single property, use[ JsonPropertyName] characteristic.

Property name for this property setting:

  • Works in both directions (serialization and deserialization).
  • Takes precedence over attribute naming policies.

demo:

/// <summary>
///Author
/// </summary>
[JsonPropertyName("author")]
public string Author
{
    get { return _author; }
    set { _author = value; }
}

JsonIgnore ignores individual attributes

Prevent serialization or deserialization of properties.

demo:

/// <summary>
///Book publisher
/// </summary>
[JsonIgnore]
public string OutCompany { get => _outCompany; set => _outCompany = value; }

JsonExtensionData processing overflow JSON

During deserialization, data not represented by the attributes of the target type may be received in JSON. These data that cannot be represented by the attributes of the target type can be stored in a dictionary < string, jsonelement > dictionary as follows:

/// <summary>
///Storing overflow data during deserialization
/// </summary>
[JsonExtensionData]
public Dictionary<string, JsonElement> ExtensionData { get; set; }

The author's choice

In the author's development experience, json mostly uses front and back-end data transmission and database storage. These options are often selected for jsonSerializerOptions:

JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
    // Neat printing
    WriteIndented = true,
    // Ignoring property with Null value
    IgnoreNullValues = true,
    // Sets the encoding supported by the Json string. By default, the serializer will escape all non ASCII characters. That is, they will be replaced with \ uxxxx, where xxxx is the Unicode of the character
    // Code. The generated josn string can be serialized without escaping the specified character set by setting Encoder. The following specifies the basic Unicode block of the Basic Latin letter and the unified ideograph of China, Japan and South Korea
    // (U+4E00-U+9FCC). It basically covers the languages of all western countries except Cyrillic letters and the languages of China, Japan, South Korea and Vietnam in Asia
    Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs, UnicodeRanges.CjkSymbolsandPunctuation),
    // Deserialization is not case sensitive
    PropertyNameCaseInsensitive = true,
    // Hump naming
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    // Hump naming of dictionary keys
    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
    // The read-only attribute is ignored. Because the read-only attribute can only be serialized and cannot be deserialized, serializing the read-only attribute is of little significance when json is used as the medium for storing data
    IgnoreReadOnlyFields = true,
    // Allows strings that should have been numbers (numbers with quotes) to be converted to numbers during deserialization
    NumberHandling = JsonNumberHandling.AllowReadingFromString
};

Try not to use the JsonPropertyName attribute. For classes that may use json deserialization, you must use the JsonExtensionData attribute to store possible overflow data. JsonIgnore and JsonInclude will be widely used instead of the IncludeFields of JsonSerializerOptions to sequence all fields.

LICENSE

All references to other articles have been clearly marked, and other parts are the author's labor achievements. Make the following statement on the author's labor achievements:

copyright © 2021 Su Yuesheng, all rights reserved.


This work is adopted by Su Yuesheng Knowledge sharing Attribution - non-commercial use - sharing in the same way 4.0 international license agreement License.

Posted by microthick on Sun, 28 Nov 2021 22:05:30 -0800