C # collection of common functions

Source: Internet
Author: User
Tags natural logarithm
1. DateTime numeric type
System. DateTime currentTime = new
System. DateTime ();
1.1 take the current year, month, day, hour, minute, second

CurrentTime = System. DateTime. Now;
1.2 get current year
Int
Year = currentTime. Year;
1.3 take the current month
Int
Month = currentTime. Month;
1.4 get the current day
Int
Day = currentTime. Day;
1.5 current time
Int
Time = currentTime. Hour;
1.6 get the current score
Int
Minute = currentTime. Minute;
1.7 takes the current second
Int
Seconds = currentTime. Second;
1.8 takes the current millisecond
Int
Millisecond = currentTime. Millisecond;
2. Int32.Parse (variable) Int32.Parse (constant)
(The variable can be in Chinese)
Convert string to 32-digit font
1.9 display Chinese date -- year, month, and day

String strY = currentTime. ToString (f); seconds not displayed
1.10 use Chinese date to display _ year and month

String strYM = currentTime. ToString (y );
1.11 retrieve Chinese Date display _ month/day

String strMD = currentTime. ToString (m );
1.12
The current year, month, and day. Format: 2003-9-23
String
StrYMD = currentTime. ToString (d );
1.13 get the current time, format: 14: 24

String strT = currentTime. ToString (t );
3. Variable. ToString ()

Convert string to string
12345. ToString (n); generate 12,345.00

12345. ToString (C); generate $12,345.00
12345. ToString (e); generated
1.234500e + 004
12345. ToString (f4); generate 12345.0000

12345. ToString (x); generate 3039 (hexadecimal)
12345. ToString (p); generated
1,234,500.00%
4. Variable. Length numeric type
String Length:
For example, string
Str = China;
Int Len = str. Length; Len is a custom variable, and str is the variable name of the string to be tested.

5. System. Text. Encoding. Default. GetBytes (variable)
Convert character code to bit code

For example, byte [] bytStr = system. Text. Encoding. Default. GetBytes (str );

Then we can get the bit length:
Len = bytStr. Length;

6. System. Text. StringBuilder ()
String addition, (is the same as the + number ?)

For example, System. Text. StringBuilder sb = new system. Text. StringBuilder ();

Sb. Append (China );
Sb. Append (people );
Sb. Append (Republic of China );

7. Variable. Substring (parameter 1, parameter 2 );
Similar to the Left, right, and Mid functions in vb.

Part of the string to be truncated. Parameter 1 is the start number of digits on the left, and parameter 2 is the number of digits to be truncated.
For example, string s1 =
Str. Substring (0, 2 );
Parameter 2 can be set to the default value, indicating that the string end is obtained from parameter 1. For example:
String a =
Abc;
A. substring (1)
Is bc.
8. String
User_IP = Request. ServerVariables [REMOTE_ADDR]. ToString (); obtain the remote user IP Address

9. Obtain the real IP address of the remote user through the proxy server:

If (Request. ServerVariables [HTTP_VIA]! = Null)
{
String
User_IP = Request. ServerVariables [HTTP_X_FORWARDED_FOR]. ToString ();

}
Else
{
String
User_IP = Request. ServerVariables [REMOTE_ADDR]. ToString ();
}
10,
Session [variable];
Access Session value;
For example, assign a value:
Session [username] = Obama;
Value: Object
ObjName = Session [username];
String
StrName = objName. ToString ();
Clear: Session. RemoveAll ();
11. String
Str = Request. QueryString [variable];
Use hyperlinks to send variables.
For example, create a hyperlink on any page
Href = Edit. aspxfbid = 23 click
On the Edit. aspx page, set the value to String.
Str = Request. QueryString [fdid];
12. DOC object. CreateElement (new node name );

Create a new node for the XML document
13. parent node. AppendChild (child node );
Add the new child node to the XML document parent node.

14. parent node. RemoveChild (node );
Delete a node
15. Response

Response. Write (string );
Response. Write (variable );
Output to the page.

Response. Redirect (URL address );
Jump to the page specified by the URL

16. char. IsWhiteSpce (STRING variable, digits) -- Logical type
Check whether the specified position contains null characters;

For example:
String str = People's Republic of China;

Response. Write (char. IsWhiteSpace (str, 2); Result: True, the first character is 0, 2 is the third character.

17. char. IsPunctuation ('characters') -- Logical type
Check whether a character is a punctuation mark.

For example: Response. Write (char. IsPunctuation ('A'); Return: False

18. (int) 'characters'
Convert the character into a number and check the code. Note that it is a single quotation mark.
For example:

Response. Write (int) '); the result is the code of the Chinese character: 20013
19. (char) Code

Convert the number into characters and check the characters represented by the Code.
For example:
Response. Write (char) 22269 );
Returns the country name.
20. Trim ()
Clear leading and trailing Spaces
21
, String variable. Replace (Child string, Replace)
String replacement
For example:
String
Str = China;
Str = str. Replace (national, central); Replace the national character with the central character
Response. Write (str );
The output result is central.
Another example is: (this is very practical)
String str = This is a script;

Str = str. Replace (, fontfont); Replace the left angle brackets with font and
(Or change to, but it is estimated that after saving XML, it will be restored again)
Response. Write (str );
Shown as: This is a script
If it is not replaced, the script will not be displayed. If it is a script, it will run. If it is replaced, the script will not run.

The value of this Code is that you can invalidate and display all HTML tags in a text file to protect your interactive websites.

Specific implementation: Add the following code to your form submission button script:
String strSubmit = label1.Text;
Label1 is the ID of the control that allows the user to submit data.

StrSubmit = strSubmit. Replace (, fontfont );
Then save or output strSubmit.

This method can also be used to easily implement the UBB code.
22. Math. Max (I, j)
Take the maximum value in I and j.
Such as int
X = Math. Max (5, 10); x is set to 10.
23. For string comparison, if (str1 = str2 ){},
But there are other methods.
(1 ),
String str1; str2
Syntax
Str1.EndsWith (str2); _ checks whether str1 ends with str2 and returns a Boolean value, as shown in figure

If (str1.EndsWith (str2) {Response. Write (string str1 ends with + str2 + );}

(2 ),
Syntax str1.Equals (str2 );
_ Check whether str1 is equal to str2. A boolean value is returned. The usage is the same as that of str2.
(3 ),
Syntax
Equals (str1, str2); _ checks whether str1 is equal to str2 and returns a Boolean value.
24. IndexOf ()
, LastIndexOf ()
Search for the position where the specified character or string appears for the first time (the last time) in the string, and return the index value, for example:

Str1.IndexOf (Word); search for the index value (location) of a word in str1)

Str1.IndexOf (string); searches for the index value (position) of the first character of the string in str1)

Str1.IndexOf (string, 4th); search for 2 characters starting from str1 and the index value (position) of the first character of the string in str1)

25. Insert ()
Insert the specified character into the specified index position in the string. For example:

Str1.Insert (1, word); insert a word at the second character of str1. If str1 = China, It is inserted as a Chinese character;

26. PadLeft (), PadRight ()
Add a space or a specified char character to the left (or right) of the string so that the string reaches the specified length, for example:

%
String str1 = Chinese;
Str1 = str1.PadLeft (10, '1 ');
No second parameter is added with Space
Response. Write (str1); the result is 1111111 Chinese, and the string length is 10

%
27. Remove ()
Deletes a specified number of characters from a specified position.
String comparison is generally used
If (str1 = str2) {}, but there are other methods
1,
String str1;
Str2
Syntax str1.EndsWith (str2); _ checks whether str1 ends with str2 and returns a Boolean value, as shown in figure

If (str1.EndsWith (str2) {Response. Write (string str1 ends with + str2 + );}

2,
Syntax str1.Equals (str2); _ checks whether str1 is equal to str2 and returns a Boolean value.

3,
Syntax Equals (str1, str2); _ checks whether str1 is equal to str2 and returns a Boolean value.

IndexOf ()
Searches for the position of the specified character or string that appears for the first time in the string, and returns the first index value, for example:
Str1.IndexOf (Word );
Search for the index value (location) of a word in str1)

Str1.IndexOf (string); searches for the index value (position) of the first character of the string in str1)

Str1.IndexOf (string, 4th); search for 2 characters starting from str1 and the index value (position) of the first character of the string in str1)

================= Asp.net (C #) common Function tables ===============================
Abs (number)
Obtain the absolute value of a value.
Asc (String) obtains the first ASCII code of a String expression.
Atn (number)
Returns the arc tangent of an angle.
CallByName (object, procname, usecalltype, [args ()])
Executes the method, setting, or returning the attributes of an object.
The CBool (expression) Conversion expression is Boolean.
Type.
The CByte (expression) Conversion expression is a Byte type.

The CChar (expression) Conversion expression is a character type.
CDate (expression)
The conversion expression is of the Date type.
CDbl (expression) Conversion expression is Double
Type.
The CDec (expression) Conversion expression is of the Decimal type.

The CInt (expression) Conversion expression is of the Integer type.
CLng (expression)
The conversion expression is of the Long type.
CObj (expression) Conversion expression is Object
Type.
The CShort (expression) Conversion expression is of the Short type.

The CSng (expression) Conversion expression is of the Single type.
CStr (expression)
The conversion expression is of the String type.
Choose (index, choice-1 [, choice-2 ,...[,
Choice-n]) Select and return the set parameters based on the index value.
Chr (charcode) uses ASCII
To obtain the character content.
Close (filenumberlist) ends the archive enabled with Open.

Cos (number) gets the cosine of an angle.
Ctype (expression, typename)
Type of the conversion expression.
DateAdd (dateinterval, number, datetime)
Add or subtract the date or time.
DateDiff (dateinterval, date1, date2)
Calculate the difference between two dates or times.
DatePart (dateinterval, date)
Return year, month, day, or time based on the received date or time parameter.
DateSerial (year, month, day)
Combine the received parameters into a data of Date type only with Date.
DateValue (datetime)
Obtain the date value that matches the country-specific style and contains the time.
Day (datetime) is returned to the date based on the received date parameter.

Eof (filenumber) returns True when it reaches the end of an opened file.
Exp (number) returns e Based on the received Parameter
.
FileDateTime (pathname) returns the date and time when the file was created.

The length of the file returned by FileLen (pathname) in bytes.
Filter (sourcearray, match [,
Include [, compare])
Search for the specified string in the string array. If the array element contains the specified string, it is combined into a new string array and returned. If you want to return an array element that does not contain the specified string, include
Set the parameter to False. The compare parameter is used to set whether the search is case sensitive. In this case, you only need to give TextCompare constants or 1.

Fix (number) removes the fractional part of the parameter and returns the result.
Format (expression [, style [,
Firstdayofweek [, firstweekofyear]) converts the date, time, and numerical data into a format acceptable to each country.

FormatCurrency (expression [, numdigitsafterdecimal [, includeleadingdigit])
Output the value as the amount type.
The numdigitsafterdecimal parameter indicates the number of decimal words.
If the integer is 0, whether to add the number of words to the integer.
FormatDateTime (date [, namedformat])
Returns formatted date or time data.
FormatNumber (expression [, numdigitsafterdecimal
[, Includeleadingdigit]) returns the format
. Numdigitsafterdecimal
The parameter is a decimal number of words, and the deleadingdigit parameter is whether to add the number of words to the integer when the integer is 0.

FormatPercent (expression [, numdigitsafterdecimal [, includeleadingdigit])
Return numeric data converted to percentage format. The numdigitsafterdecimal parameter indicates the number of decimal words, and the "When deleadingdigit" parameter indicates that the integer is 0.
Whether to fill in the integer word count.
GetAttr(2005620163726.htm) returns the attribute value of the file or directory.

Hex (number) converts a value to a hexadecimal value.
The Hour field of the time returned by Hour (time). The type is Integer.
.
Iif (expression, truepart, falsepart): When the return value of the expression is True, truepart is executed.
The program of the field. Otherwise, the falsepart field is executed.
InStr ([start,] string1, string2) Search for string2
The character set by the parameter appears in the character string, start is used to search for the character, string1 is the string to search, string2
It is the character to be searched.
Int (number) returns an integer smaller than or equal to the maximum integer of the received parameter.
IsArray (varname)
Determines whether a variable is an array type. If it is an array, True is returned. Otherwise, False is returned.
IsDate (expression)
Determines whether the expression content is of the DateTime type. If the expression content is of the DateTime type, True is returned. Otherwise, False is returned.
IsDbNull (expression)
Determines whether the expression content is Null. If the expression content is Null, True is returned. Otherwise, False is returned.
IsNumeric (expression)
Determines whether the expression content is Numeric. If the expression content is True, False is returned.
Join (sourcearray [, delimiter])
Merges string arrays into unique strings. The delimiter parameter is used to add new strings to each element.
Lcase (string)
Converts a string to a lowercase font.
Left (string, length) is obtained from the Left side of the string.
The parameter specifies the characters in length.
Len (string) gets the length of the string.
Log (number)
Obtain the natural logarithm of a value.
Ltrim (string) removes the left blank part of the string.
Mid (string, start [,
Length]) retrieves the string of the length after the character set by the strat parameter in the string. If the length parameter is not set, the start
All subsequent characters.
Minute (time) gets the time content of the part, type is Integer.
MkDir (path)
Create a new directory.
Month (date) indicates the Month of the date. The type is Integer.

MonthName (month) is used to obtain the complete description of the month based on the received month value.
Now () gets the current date and time.

Oct (number) converts a value to an octal value.
Replace (expression, find, replace)
Convert the string specified by the find parameter in the string to the string specified by the replace parameter.
Right (string, length)
Gets the characters with the length parameter set from the right side of the string.
RmDir (path) removes an empty directory.
Rnd ()
Returns a decimal number between 0 and 1. If you want to obtain different values each time, you must add Randomize before use.
Rtrim (string)
Removes the white space on the right of the string.
The Second part of the time content obtained by Second (time). The type is Integer.

Sign (number) indicates whether the value is positive or negative. If the value is positive, 1 is returned. If the value is negative,-1 is returned. If the value is 0, 0 is returned.
Sin (number)
Returns the sine of an angle.
Space (number) gets the blank string set by the number parameter.

Split (expression [, delimiter]) Splits a string into a String Array Based on the condition string set by the delimiter parameter.

Sqrt (number) returns the square root of a number.
Str (number) converts a number into a string and returns it.

StrReverse (expression) returns the result after the string content is reversed.
Tan (number)
Returns the tangent of an angle.
TimeOfDay () gets the time that does not contain the date currently.
Timer () is obtained by 000
The number of seconds of the current time. The type is Double.
TimeSerial (hour, minute, second)
Merge the received parameters into a data with only the time Date type.
TimaValue (time) gets the time value that matches the country-specific style.

Today () gets the date that Today does not contain the time.
Trim (string) removes the white space at the beginning and end of the string.

TypeName (varname) gets the type of the variable or object.
Ubound (arrayname [, dimension])
Obtain the final index value of the array. The dimension parameter is the final index value of the dimension specified to be obtained.
Ucase (string)
Converts a string to uppercase.
Val (string)
Converts a string representing a number to a numeric value. If the string contains non-numeric content, it is removed and merged into a number.
Weekday (date)
The date in the parameter is the day of the week, Sunday is 1, Monday is 2, and Tuesday is 3.
WeekDayName (number)
Obtain the name of the week based on the received parameters. The parameters that can be received are 1 to 7, Sunday is 1, Monday is 2, and Tuesday is 3.
Related Article

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.