扩展ObservableCollection<T>,增加AddRange<T>()方法

扩展ObservableCollection,实现添加集合的扩展,当集合中新增、修改或者删除项目时,或者集合被刷新时,触发通知(通过实现接口INotifyCollectionChanged)。

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace ReflectionIT.WPF {

public static class Extensions {

public static void AddRange<T>(this ObservableCollection<T> oc, IEnumerable<T> collection) {
if (collection == null) {
throw new ArgumentNullException("collection");
}
foreach (var item in collection)
{
oc.Add(item);
}


}
}
}

C#语言中的Encrypt和Decrypt

使用RSACryptoServiceProvider加密和解密一个字符串。

源代码:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Extensions
{
public static class Extensions
{
/// <summary>
/// Encryptes a string using the supplied key. Encoding is done using RSA encryption.
/// </summary>
/// <param name="stringToEncrypt">String that must be encrypted.</param>
/// <param name="key">Encryptionkey.</param>
/// <returns>A string representing a byte array separated by a minus sign.</returns>
/// <exception cref="ArgumentException">Occurs when stringToEncrypt or key is null or empty.</exception>
public static string Encrypt(this string stringToEncrypt, string key)
{
if (string.IsNullOrEmpty(stringToEncrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}

if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
}

CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;

byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);

return BitConverter.ToString(bytes);
}

/// <summary>
/// Decryptes a string using the supplied key. Decoding is done using RSA encryption.
/// </summary>
/// <param name="stringToDecrypt">String that must be decrypted.</param>
/// <param name="key">Decryptionkey.</param>
/// <returns>The decrypted string or null if decryption failed.</returns>
/// <exception cref="ArgumentException">Occurs when stringToDecrypt or key is null or empty.</exception>
public static string Decrypt(this string stringToDecrypt, string key)
{
string result = null;

if (string.IsNullOrEmpty(stringToDecrypt))
{
throw new ArgumentException("An empty string value cannot be encrypted.");
}

if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot decrypt using an empty key. Please supply a decryption key.");
}

try
{
CspParameters cspp = new CspParameters();
cspp.KeyContainerName = key;

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cspp);
rsa.PersistKeyInCsp = true;

string[] decryptArray = stringToDecrypt.Split(new string[] { "-" }, StringSplitOptions.None);
byte[] decryptByteArray = Array.ConvertAll<string, byte>(decryptArray, (s => Convert.ToByte(byte.Parse(s, System.Globalization.NumberStyles.HexNumber))));


byte[] bytes = rsa.Decrypt(decryptByteArray, true);

result = System.Text.UTF8Encoding.UTF8.GetString(bytes);

}
finally
{
// no need for further processing
}

return result;
}


}
}

C#语言判断两个数据表的内容是否相同

判断两个数据表的内容是否相同

源代码:

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
public static bool EqualsByContent(this DataTable thisDataTable, DataTable otherDataTable)
{
// Compare row count.
if (thisDataTable.Rows.Count != otherDataTable.Rows.Count)
{
return false;
}

// Compare column count.
if (thisDataTable.Columns.Count != otherDataTable.Columns.Count)
{
return false;
}

// Compare data in each cell of each row.
for (int i = 0; i < thisDataTable.Rows.Count; i++)
{
for (int j = 0; j < thisDataTable.Columns.Count; j++)
{
if (!thisDataTable.Rows[i][j].Equals(otherDataTable.Rows[i][j]))
{
return false;
}
}
}

// The two DataTables contain the same data.
return true;
}

将DataReader转换为CSV

导出DataReader为CSV (List).

源代码:

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public static List<string> ToCSV(this IDataReader dataReader, bool includeHeaderAsFirstRow, string separator)
{
List<string> csvRows = new List<string>();
StringBuilder sb = null;

if (includeHeaderAsFirstRow)
{
sb = new StringBuilder();
for (int index = 0; index < dataReader.FieldCount; index++)
{
if (dataReader.GetName(index) != null)
sb.Append(dataReader.GetName(index));

if (index < dataReader.FieldCount - 1)
sb.Append(separator);
}
csvRows.Add(sb.ToString());
}

while (dataReader.Read())
{
sb = new StringBuilder();
for (int index = 0; index < dataReader.FieldCount - 1; index++)
{
if (!dataReader.IsDBNull(index))
{
string value = dataReader.GetValue(index).ToString();
if (dataReader.GetFieldType(index) == typeof(String))
{
//If double quotes are used in value, ensure each are replaced but 2.
if (value.IndexOf("\"") >= 0)
value = value.Replace("\"", "\"\"");

//If separtor are is in value, ensure it is put in double quotes.
if (value.IndexOf(separator) >= 0)
value = "\"" + value + "\"";
}
sb.Append(value);
}

if (index < dataReader.FieldCount - 1)
sb.Append(separator);
}

if (!dataReader.IsDBNull(dataReader.FieldCount - 1))
sb.Append(dataReader.GetValue(dataReader.FieldCount - 1).ToString().Replace(separator, " "));

csvRows.Add(sb.ToString());
}
dataReader.Close();
sb = null;
return csvRows;
}

C#扩展格式化方法

C#扩展格式化方法

源代码:

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
/// <summary>
/// Formats the string according to the specified mask
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="mask">The mask for formatting. Like "A##-##-T-###Z"</param>
/// <returns>The formatted string</returns>
public static string FormatWithMask(this string input, string mask)
{
if (input.IsNullOrEmpty()) return input;
var output = string.Empty;
var index = 0;
foreach (var m in mask)
{
if (m == '#')
{
if(index < input.Length)
{
output += input[index];
index++;
}
}
else
output += m;
}
return output;
}

C#语言中通过列名获取该列在excel中的索引

通过列名获取该列在excel中的索引

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static int ExcelColumnIndex(this string columnName)
{
int number = 0;
int pow = 1;

for (int i = columnName.Length - 1; i >= 0; i--)
{
number += (columnName[i] - 'A' + 1) * pow;
pow *= 26;
}

return number;
}

C#扩展foreach,可以传入action

C#扩展foreach,可以传入action

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static IEnumerable<T> ForEach<T>(this IEnumerable<T> array, Action<T> act)
{
foreach (var i in array)
act(i);
return array;
}

public static IEnumerable<T> ForEach<T>(this IEnumerable arr, Action<T> act)
{
return arr.Cast<T>().ForEach<T>(act);
}

public static IEnumerable<RT> ForEach<T, RT>(this IEnumerable<T> array, Func<T, RT> func)
{
var list = new List<RT>();
foreach (var i in array)
{
var obj = func(i);
if (obj != null)
list.Add(obj);
}
return list;
}

InsertSorted

Insert an item to a sorted List

源代码:

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
40
41
42
43
44
static class Extensions {

public static int InsertSorted<T>(this IList<T> source, T value) where T : IComparable<T> {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (value.CompareTo(source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}

public static int InsertSorted<T>(this IList<T> source, T value, IComparer<T> comparison) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (comparison.Compare(value, source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}

public static int InsertSorted<T>(this IList<T> source, T value, Comparison<T> comparison) {
if (source is null) {
throw new ArgumentNullException(nameof(source));
}
for (int i = 0; i < source.Count; i++) {
if (comparison(value, source[i]) < 0) {
source.Insert(i, value);
return i;
}
}
source.Add(value);
return source.Count - 1;
}
}

IsValidUrl

Returns true when a string is a valid url

源代码:

1
2
3
4
5
6
7
public static class MyExtensionMethods {
public static bool IsValidUrl(this string text) {
Regex rx = new Regex(@"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?");
return rx.IsMatch(text);
}
}
}

Reverse

Reverse a string

源代码:

1
2
3
4
5
6
7
8
9
static class Helpers
{
public static string Reverse(this string s)
{
char[] c = s.ToCharArray();
Array.Reverse(c);
return new string(c);
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×