C # Basics

Source: Internet
Author: User
Tags bit set
Document directory
  • Elements of the linq language:
  • Run the query:
  • Set operations outside of linq:
  • Differences between fields and attributes:
  • Interface:
  • Delegation and events:
  • Generic:
1. Covariant Inverter

A set of keywords, out and in

Covariant: I <out object >= I <sting>

Inverter: I <in string> = I <objet>

Ps. The generic instance does not have an inheritance relationship.

Ps. In essence, instance algorithms are called. The covariant interface is open. As long as the subclass parameter is defined, the special case algorithm can be called. The inverter interface is closed and can only call the algorithm of the parent parameter.

The covariant inverter does not support value type parameters, does not support ref or out function parameters, and does not support generic constraints as interface methods. This interface cannot be nested with classes, enumerations, or structures.

The covariant parameter can only be used as the return type of the method, and the invert parameter can only be used as the parameter type of the method.

The covariant inverter only limits the current specified object and does not pass features through inheritance.

Definition Format:

Interface I <in A, out R>

2. Key Interfaces

IEnumerable <out T>: a set of simple iterations. This interface only returns IEnumerator <out T>.

IEnumerator <T> GetEnumerator ()

IEnumerator <out T>: IDisposable,

Dispose ()

Bool MoveNext (): enumeration of the next element. If it exceeds the end, it is false.

Reset (): Only use com objects.

T Current: the Current position element. It is the first element after MoveNext.

IQueryable <out T>: IEnumerable <T>, supports different data source query types.

IEnumerator <T> GetEnumerator ()

Type ElementType: Element Type

Expression: Expression directory tree

IQueryProvider Provider: The Provider that creates an IQueryable instance.

IGrouping <out TKey, out TElement>: IEnumerable <TElement> indicates a set with a public key.

IEnumerator <TElement> GetEnumerator ()

TKey: Key

IComparer <in T>: comparison algorithm

Int Compare (T, T): negative value less than, zero equals, positive value greater than, null less than any reference

IEqualityComparer <in T>: Equality Algorithm

Bool Equals (T, T)

Int GetHashCode (T): If the two objects are equal, the hash value must be equal.

IComparable <in T>: comparable object

Int CompareTo (T)

IEquatable <in T>: equivalent objects can be compared.

Bool Equals (T)

When we find a rule (a person who does not know English can float), the end of able refers to an object to implement this interface, so that it has some characteristics. The end of er is a parameter passed to a specific method call to develop the algorithm used.

3. Key Commission

Action <in T>: void (T)

Action <in T1, in T2>: void (T1, T2)

Func <out TResult>: TResult ()

Func <in T, out TResult>: TResult (T)

Predicate <in T>: bool (T), whether the parameter meets the conditions

Comparison <in T>: int (T, T), Comparison algorithm, and IComparer <in T> are delegate, not objects.

Converter <in TInput, out TOutput>: TOutput (TInput), conversion algorithm

4. Integrated Query in the linq Language

The following three steps: obtain the data source, create a query, and execute a query.

Linq supports querying arbitrary objects of the IEnumerable <out T> interface.

You can create a query that connects, filters, sorts, groups, and maps data sources.

Elements of the linq language:

From: Specifies the data source. Format: from range variable in Data Source

Data source: any object that implements IEnumerable <out T>

Range variable: availableLetClause adds a new range variable. A range variable can only have one value or one expression definition (which can contain another range variable ).

 

Join: Equivalent join, which establishes an association for a sequence without explicit modeling. The two sequences must be shared to determine whether they are equal. Format: from x in X join y in Y on x. ID equals y. ID

Join only supports equal join, but there are three forms: Internal join, Group join, and left external join.

Internal join: the element of the first set matches each element of the second set. If the second set does not match, no results are generated. If n matching items exist, n results are returned.

IntoClause: Group join, so that the results of the internal join are similar to the group results, but there is no key. Essentially, it is a set of sequences of multiple groups. The number of elements in the first set is the number of groups, and the matching items in the second set are the elements of the reorganization.

. DefaultIfEmpty(DefaultObj): When the matching is null, that is, an empty sequence, this function is called to generate a sequence of default elements. This is the left Outer join, which is based on group join. Format: join... Into G from g in G. DefaultIfEmpty (...)

 

Non-equivalent join: Multiple from data sources are introduced to achieve cross-join results; low efficiency, but range variables can be introduced by let, and equivalent join is supported.

 

Where: Filter, format: where condition expression

 

Orderby: Sorting, sorting of result sets, ascending in ascending order, descending in descending order, format: ascending, which is specified by the returned Sequence

 

Group: Group, grouped by the specified key pair sequence. Format: the Key of the sequence by group returned by group

Into: can be used to define the range variable of the grouping result to continue to operate the result. Format: group x by x. key into xGroup.

 

Select: Map to result set

 

Ps.Key combination: Multiple keys are used to define matching. Key matching depends on the attribute name and sequence, but new names can be assigned.

Run the query:

Only query commands are saved in the linq variable, and specific query operations are performed using statements such as foreach and related functions.

ToList <TSource> (): returns the result set packaged in List.

ToArray <TSource (): returns the result set encapsulated by Array.

The second type is Aggregate functions (that is, return a single value ):

Count (): number of items in the statistical result set

Max ():

Average (): calculates the Average value of a sequence.

First (): returns the First entry of the result set.

......

Ps. In theory, each IEnumerable <out T> object can only be queried once.

Set operations outside of linq:

Standard linq only supports join, filter, sort, group, and ing operations. Therefore, some operations on the set are hard to be implemented using linq.

Aggregate functions:

This function is used to determine the existence of elements, set equality, aggregate feature values (maximum value, minimum value, average value, number, sum), and extract specified elements.

Predicate: Func <T, bool>

Comparer: IEqualityComparer <T>

Coverter: Func <TInput, TOutput>

S: IEnumerable <T>

 

Bool All (predicate): determines whether All elements in the Set meet the conditions. If the empty set is used, true is returned.

Bool Any (): returns true if the element is included.

Bool Any (predicate): returns true if it contains elements that meet the conditions.

Bool Contains (T): determines whether a sequence has a given element and uses the Default equal comparator.

Bool Contains (T, comparer): Same as above, specifying a comparator

 

Bool SequenceEqual (S): compare whether the two sequences are equal

Bool SequenceEqual (S, comparer): Same as above, with the specified Comparator

 

T Aggregate (Func <T aggregation, T Elements, T aggregation>): through iterative custom aggregation

X Aggregate (X aggregation, Func <X aggregation, T Elements, X aggregation>): Same as above, specifying the Aggregate variable

X Aggregate (X, Func <X, T, X>, coverter): Same as above, add the final Aggregate conversion function.

T Average (): the Average value of the sequence. An error occurred while the empty set was empty.

X Average (coverter): Specifies the Conversion Function and calculates the Average value. An exception occurs when the empty set is used.

Int Count (): number of sequence elements. function for a larger range: long LongCount ()

Int Count (predicate): number of elements that meet the conditions

X Max (): returns the largest element in the sequence. The null set is abnormal. Use the IComparable <T> comparison interface.

X Max (coverter): Specifies the Conversion Function and returns the largest element of the sequence.

X Min (): Minimum sequence element

X Min (coverter ):

X Sum (): sequence and

X Sum (coverter): The converted sequence and

 

T ElementAt (int): returns the element of the custom position.

T ElementAtOrDeflault (int): Same as above. If the range is exceeded, the default value is returned.

T First (): the First element of the sequence

T First (predicate): the First element that meets the condition

T FirstOrDefault (): returns the first element. If no default value is returned

T FirstOrDefault (predicate): returns the first element that meets the condition. If no default value is returned

T Last (): returns the Last element of the sequence.

T LastOrDefault (): Same as above. If no default value is returned

T Last (predicate ):

T LastOrDefault ():

T Single (): returns the unique element of the sequence.

T Single (predicate): returns the unique element of the sequence that meets the condition.

T SingleOrDefault (): If the sequence is null, the default value is returned.

T SingleOrDefault (predicate): If none of the conditions are met, the default value is returned.

 

Set conversion:

Implement the following functions: concatenate, Set Operations (difference, union, and intersection), remove duplicate elements, reverse sequences, extract sequence paragraphs, generate or convert Sequences

S: IEnumerable <T>

Predicate: Func <T, bool>

Comparer: IEqualityComparer <T>

 

S Concat (S): concatenates two sequences

S Distinct (): returns a sequence composed of non-repeating elements. Equal comparator through EqualityComparer <T>. Default

S Reverse (): returns the Reverse sequence of elements.

S t (S): returns the difference between the first set and the second set. This operation does not conform to the exchange rate, through the Default equal Comparator

S Except (S, comparer): Same as above, specifying a comparator

S Intersect (S): returns the intersection of the two sets (the two sets share the elements, and remove the repeated elements), using the Default Comparator

S Intersect (S, comparer): Same as above, specifying a comparator

S Union (S): returns the Union of the two sets (Union, but deduplication), using the Default comparator.

S Union (S, comparer): Same as above, specifying a comparator

 

S Skip (int): skips the first n elements and returns the remainder of the sequence.

S SkipWhile (predicate): skips the elements that meet the condition until the first element that does not meet the condition is met, and returns the remaining sequence.

S SKipWhile (Func <T, int, bool>): Same as above, but the element position is input to the condition function.

S Take (int): returns a sequence composed of the First n elements.

S TakeWhile (predicate): returns a sequence of elements that meet the conditions until the first element that does not meet the conditions is met.

S TakeWhile (Func <T, int, bool>): Same as above. input the element location to the condition function.

 

S DefaultIfEmpty (): Return non-empty set

S DefaultIfEmpty (T): returns a non-empty set and specifies the default value of the element.

S Empty (): returns an Empty set.

S Range (int start, int count): generates an integer sequence of the specified Range

S Repeat (T, int count): generate a sequence of repeated elements of a specified number

S AsEnumerable (): returns the base class implementation

IQueryable <T> AsQueryable (): The IQueryable query interface is returned.

S OfType (): a sequence converted to a specified type. If an element cannot be converted, it is automatically ignored.

T [] ToArray (): Convert to array

List <T> ToList (): Convert to List

Dictionary <TKEY, TValue> ToDictionary (......) : Convert to Dictionary

Lookup <TKey, TElement> ToLookup (......) : Convert to a key combination structure Sequence

 

5. Object-oriented

ABSTRACT Data Type Definition: a single type of method is formed by combining several types of fields according to certain semantics.

Object: This type is based on abstract data types, but it restricts and interferes with external operations to form an object type with autonomy.

Object-oriented: objects are operated based on interfaces instead of directly operated on objects.

 

The idea of Object design is to maintain autonomy, reduce external intervention, and maintain the correctness of the individual, while the correctness of the individual ensures the correctness of the system.

The idea of object-oriented design is: the object's dependence on the outside world should be isolated through interfaces. When an external object fails, it can access the new object through the same interface.

The object design is based on the internal perspective. The core content is to maintain its correctness and semantic cohesion. The object orientation is based on the external perspective, and the core content is to reduce the coupling between objects.

 

Object-oriented syntax elements:

Field: Data Segment required for semantic implementation

Attribute: Controllable Field

Method: controllable operation interface, parameterized control object status

Constructor: object initialization

Destructor: Object destructor

Event: communication interface of the object, parameterized communication content

Delegate: assign a task to an external object

Nested class: Partial refinement of object definitions.

Access permission: controls the exposed Interface

Static members: shared areas of the same type (do not expose them)

Anonymous type: simple abstract data type, which can only be used temporarily

Interface: standardized operation interface (defined from the user's perspective)

Generic parameters: generalized programming methods of basic types, but each instance is strongly typed. Used for classes, structures, interfaces, and methods.

Value Type and reference type: Structure and enumeration are value types. value types are allocated in an internal manner without independent allocation, so they are high-performance.

Indexer: imitates the syntax sugar of the array.

Differences between fields and attributes:

Fields are unrestricted and attributes are controllable. If fields do not need to be controlled, you can use fields. Otherwise, you should hide the fields and use them as the operation interface. The value range is equal to the value range of the type. It is independent of other fields and is not associated with transactions. It is not read-only or write-only.

Interface:

Interfaces can be combined by methods, attributes, events, and indexers.

Indexer: T this [T1 index,…] {Get; set ;}

Differences between explicit and implicit interfaces:

1. explicitly implemented accessors must match (set; get ;).

2. Members must be made public by implicit implementation.

3. explicitly implementing access failure through class instances, but need to be converted to this interface for access

4. The accessors (add; remove;) are required for explicitly implemented events ;)

5. explicit implementation format :... Interface Name. Member...

Delegation and events:

1. The event adds a subscriber through + =, and-= deletes the subscriber. If there is no subscriber, the event instance is null.

2. The standard event is based on EventHandler <T> delegate: void (object sender, T e) where T: EventArgs

3. You can customize the event accessors in the following format:

Add {lock (event field ){...}} // Prevent thread Problems

Remove {lock (event field ){...}}

4. Static event sender = null. Non-static sender is not empty. E should not be blank and can be replaced by EventArgs. Empty

5. events triggered and processed are synchronized by default. At the same time, event processing may lead to unprocessed events, causing program crash.

6. The relationship between events and delegation is similar to that between attributes and fields. For the relative attribute of an event, only the + = and-= operations are supported, instead of the value assignment and read operations.

7. Explicit events (with accessors) do not automatically generate the corresponding delegate and corresponding accessors.

Generic:

Generic objects: interfaces, classes, methods, events, and delegation.

Generic constraints provide both generic constraints and the same capabilities. Constraints and capabilities are mutually compatible.

When a generic parameter is referenced, only one piece of code is generated, and corresponding code is generated according to different value types.

All code versions of the generic type are logically consistent, with no special columns.

Constraints:

Where T: struct // it can only be a value type

Where T: class // can only be a reference type

Where T: new () // requires a default constructor

Where T: base class or interface

Where T: U // U is also a generic parameter; T is derived from U.

Ps. Indicates the operation that the compiler can use. When the constraint is class and the object is overloaded = ,! = The operator is invalid.

Ps. The unrestricted parameter cannot be used! =, = Operator, but can be compared with null.

Ps. Default (T) is used to generate the default value. The value type is 0, the structure member is 0, and the reference is null.

 

6. Lambda

Lambda expressions are anonymous functions that can be used to create a delegate or Expression Tree.

Lambda statements (multi-line statements in braces) cannot be used to create expression trees.

Example:

() => ....

X =>...

(X, y) =>...

7. Iterator

The iterator is a powerful syntax sugar: the current item of the iteration is returned immediately using the yield keyword to generate a nested class to record the position of the current iteration. The iterator method returns the IEnumerable <out T> or IEnumerator <out T> object.

The iterator is the basis for the latency query of LINQ.

The Nested classes generated by the iterator can generate the corresponding logic based on the internal statements of the iterator method. Therefore, the Implementation Effect of the nested classes is similar to that of manually writing IEnumberable <out T>, you only need to use yield in bold.

Ps. The efficiency of the iterator code is less than that of the handwritten code.

Syntax:

Yield break // terminate Iteration

Yield return T // return the current item

Note: The yield return here cannot be returned by the current function (the current function directly returns nested class objects ), this information is required for the implementation of Nested classes to set the items returned by enumeration and where to suspend execution and where to continue execution. Each enumeration element corresponds to a yield return: The next enumeration continues after this statement until the next yield return is met and the current element is returned.

 

8. Set and Data Structure

The. Net collection contains commonly used data structures: arrays, lists (sorting lists), dictionaries (hash tables), queues, stacks, and packages.

Each collection may have several versions with different features: thread-safe sets, sorted sets, and read-only sets.

Generic version of thread security: System. Collections. Concurrent

Generic version: System. Collections. Generic

Normal version: System. Collections

Mappings between versions:

List corresponding to ArrayList <T>

Hashtable corresponds to Dictionary <TKey, TValue>, ConcurrentDictionary <TKey, TValue>

Collection corresponding to CollectionBase <T>

ReadOnlyCollectionBase corresponds to ReadOnlyCollection <T>

Queue corresponds to Queue <T> and ConcurrentQueue <T>

Stack <T>, ConcurrentStack <T>

SortedList corresponds to SortedList <T> and ConcurrentSortedList <T>

No common version:

Revoke list <T>

SortedDictionary <TKey, TValue>

KeyedCollection <TKey, TItem>

BlockingCollection <T>

ConcurrentBag <T>

Set interface:

1. ICollection

2. IList and IDictionary

Ps. 2 inherits 1

Ps. The IDictionary element must implement the IComparer <T> size comparator interface.

ICollection implementation: Queue, ConcurrentQueue <T>, Stack, ConcurrentStack <T>, consumer list <T>, KeyedCollection <TKey, TItem>

Implementation of IList: Array, ArrayList, List <T>

Implementation of IDictionary: Hashtable, SortedList, Dictionary <TKey, TValue>, SortedList <TKey, TValue>, ConcurrentDictionary <TKey, TValue>

Mathematical set (a set with unique elements ):

ISet <T>

HashSet <T>

SortedSet <T>

Bit Set:

BitVector32

BitArray

Other sets:

StringCollection

StringDictionary

CollectionUtil

HybridDictionary

ListDictionary

NameValueCollection

NameObjectCollectionBase

BlockingCollection <T>

IProducerConsumerCollection <T>

ConcurrentBag <T>

 

9. File and registry

 

10. String and Regular Expression

 

11. Logical Reasoning

Topic: reasoning about Program correctness.

 

12. Combination Arrangement

Topic: discusses how to raise the question domain.

 

13. Trigonometric function

 

14. Structure, algorithm, and ing relationship

Topic: How to build the data structure with the highest algorithm efficiency for specific problems.

 

 

 

 

 

 

 

 

 

 

To be continued ......

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.