Introduction Ever since I started using extension methods, I couldn't stop using them. They have greatly improved the efficiency of my code writing, and now I have become highly dependent on them. I would like to share my commonly used extension method set here for everyone’s convenience.
(Some of them are borrowed or appropriated from other bloggers' articles. I would like to especially thank He Chongtian for his many sharings)
Source code is provided at the end of the article.
Example
public static string ExpandAndToString(this System.Collections.IEnumerable s, string spacer character)
Function: Expand the collection and execute the ToString method respectively, and then connect them with the specified delimiter to splice them into a string.
example:
[TestMethod]
public void TestMethod1()
{
var i = new int[] {1,5,33,14,556};
var Out="1-5-33-14-556";
Assert.AreEqual(Out,i.ExpandAndToString("-"));
}
public static bool IsNullOrEmpty(this string s)
Function: Verify whether the string object is an empty object or an empty string.
example:
[TestMethod]
public void TestMethod2()
{
string s = null;
Assert.AreEqual(true,s.IsNullOrEmpty());
s += "123";
Assert.AreEqual(false, s.IsNullOrEmpty());
}
public static string IsNullOrEmptyThen(this string s, System.Func<string,string> expression)
Function: Verify whether the string object is an empty object or an empty string. If so, execute the incoming expression and return the expression result.
example:
[TestMethod]
public void TestMethod3()
{
vars = "";
var Out = "1234";
Assert.AreEqual(Out, s.IsNullOrEmptyThen(f=>"1234"));
}
public static void IsNullOrEmptyThen(this string s, System.Action<string> expression)
Function: Verify whether the string object is an empty object or an empty string, and if so, execute the incoming expression.
example:
[TestMethod]
public void TestMethod4()
{
vars = "";
s.IsNullOrEmptyThen(f => MessageBox.Show("No content"));
}
public static string FormatWith(this string s, params object[] format parameters)
public static string FormatWith(this string s, object format parameter 1)
public static string FormatWith(this string s, object format parameter 1, object format parameter 2)
public static string FormatWith(this string s, object format parameter 1, object format parameter 2, object format parameter 3)
Function: Format string.
example:
[TestMethod]
public void TestMethod5()
{
var i = 0.35;
var x = 200;
var Out = "i:35%;x:200;";
Assert.AreEqual(Out, "i:{0:0%};x:{1};".FormatWith(i,x));
}
public static bool In<T>(this T t, params T[] judgment basis)
Function: Determine whether the current object is in the incoming array.
example:
[TestMethod]
public void TestMethod6()
{
var i = 95;
Assert.IsTrue(i.In(31, 3, 55, 67, 95, 12, 4));
}
public static bool In<T, C>(this T t, System.Func<T,C,bool> judgment expression, params C[] judgment basis)
Function: Determine whether the current object is in the incoming array. The judgment method is specified by the incoming expression.
example:
[TestMethod]
public void TestMethod7()
{
var i = 95;
Assert.IsTrue(i.In((c, t) => c.ToString() == t, "31", "3", "55", "67", "95", "12", "4 "));
}
public static bool InRange<T>(this System.IComparable<T> t, T minimum value, T maximum value)
public static bool InRange(this System.IComparable t, object minimum value, object maximum value)
Function: Determine whether the current value is within the specified range.
example:
[TestMethod]
public void TestMethod8()
{
var i = 95;
Assert.IsTrue(i.InRange(15, 100));
Assert.IsTrue(i.InRange(-3000, 300));
Assert.IsFalse(i.InRange(-1, 50));
vars = "b";
Assert.IsTrue(s.InRange("a", "c"));
Assert.IsTrue(s.InRange("1", "z"));
Assert.IsFalse(s.InRange("e", "h"));
}
public static T Trace<T>(this T t)
public static T Trace<T>(this T t, string classification)
public static T Trace<T>(this T t, System.Func<T,object> expression)
public static T Trace<T>(this T t, System.Func<T,object> expression, string classification)
Function: Output the value of the current object to the Visual Studio output window and return the original object. This function is only used to facilitate debugging and can output values at any step in the method chain without any impact on the continuity of the method chain.
example:
[TestMethod]
public void TestMethod9()
{
var s = "abcdefg".Trace(f => f.ToUpper(), "expression mode").Remove(4).Trace("normal mode");
var Out = "abcd";
Assert.AreEqual(Out, s);
//The output content is as follows:
//Expression pattern: ABCDEFG
//Normal mode: abcd
}
public static T TraceFormat<T>(this T t, string format string)
public static T TraceFormat<T>(this T t, string format string, string classification)
Function: Output the value of the current object to the Visual Studio output window after formatting, and return the original object. This function is only used to facilitate debugging. Values can be output at any step in the method chain without any impact on the continuity of the method chain.
example:
[TestMethod]
public void TestMethod10()
{
var m = Math.Max(0.31, 0.65).TraceFormat("Max Value Is {0}", "Formatting Mode");
varOut = 0.65;
Assert.AreEqual(Out, m);
//The output content is as follows:
//Format mode: Max Value Is 0.65
}
public static void ForEach<T>(this System.Collections.Generic.IEnumerable<T> source, System.Action<T> operation)
public static void ForEach<T>(this System.Collections.Generic.IEnumerable<T> source, System.Action<T,int> operation)
Function: Traverse a collection and perform specified operations. (In the overloaded form, the int type parameter passed into the expression represents the current number of loops)
example:
[TestMethod]
public void TestMethod11()
{
var l = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var c = 0;
l.ForEach(f => c += f);
varOut = 45;
Assert.AreEqual(Out, c);
l.ForEach((f, i) => c -= i);
Out = 9;
Assert.AreEqual(Out, c);
}
public static Switch<T> Switch<T>(this T v)
public static Case<T,R> Switch<T, R>(this T v, System.Func<R,R,R> Do)
Function: Determine the current value, perform corresponding operations or return corresponding values according to different matching conditions. (In the overloaded form, each return value is allowed to be superimposed through expressions)
For detailed instructions, please refer to: "Slightly Improved Switch/Case Extension Method"
example:
[TestMethod]
public void TestMethod12()
{
var i = 15;
i.Switch()
.CaseRun(15, f => MessageBox.Show("equal to 15"),false)
.CaseRun(f => f > 0, f => MessageBox.Show("greater than 0"))
.CaseRun(f => f < 0, f => MessageBox.Show("less than 0"))
.DefaultRun(f => MessageBox.Show("Equal to 0"));
var o = 'c'.Switch()
.CaseReturn('a', 1)
.CaseReturn('b', 2)
.CaseReturn('c', 3)
.CaseReturn('d', 4)
.CaseReturn(f => f > 'd', 5)
.DefaultReturn(0).ReturnValue;
Assert.AreEqual(3, o);
}
public static System.Collections.Generic.IEnumerable<T> RecursionSelect<T>(this T o, System.Func<T,IEnumerable<T>> recursive item selection expression)
public static System.Collections.Generic.IEnumerable<T> RecursionSelect<T>(this T o, System.Func<T,IEnumerable<T>> recursive item selection expression, System.Predicate<T> test expression)
Function: Select items recursively and return the final selected collection.
For a description of the relevant principles, see: "Advanced Part 7 of the Wonderful Use of C# Extension Methods: "Tree" Universal Traverser"
example:
[TestMethod]
public void TestMethod13()
{
//Get all directory collections containing subdirectories in the specified directory
var d = new DirectoryInfo(@"C:UsersPublicDownloads");
var c = d.RecursionSelect(f => f.GetDirectories(), f => f.GetDirectories().Length > 0);
MessageBox.Show(c.Count().ToString());
}
public static System.Collections.Generic.IEnumerable<T> RecursionEachSelect<T>(this System.Collections.IEnumerable o, System.Func<T,IEnumerable<T>> recursive item selection expression)
public static System.Collections.Generic.IEnumerable<T> RecursionEachSelect<T>(this System.Collections.IEnumerable o, System.Func<T,IEnumerable<T>> recursive item selection expression, System.Predicate<T> test expression Mode)
public static System.Collections.Generic.IEnumerable<T> RecursionEachSelect<T>(this System.Collections.Generic.IEnumerable<T> o, System.Func<T,IEnumerable<T>> recursive item selection expression)
public static System.Collections.Generic.IEnumerable<T> RecursionEachSelect<T>(this System.Collections.Generic.IEnumerable<T> o, System.Func<T,IEnumerable<T>> recursive item selection expression, System.Predicate <T> test expression)
Function: Traverse the current collection object, recursively select items one by one, and return the final selected collection.
For an explanation of the relevant principles, see: "Advanced Part 7 of the Wonderful Use of C# Extension Methods: "Tree" Universal Traverser"
example:
[TestMethod]
public void TestMethod14()
{
//Get all directory collections containing subdirectories in the specified directory
var l = new List<DirectoryInfo>();
l.Add(new DirectoryInfo(@"C:UsersSkyDDownloads"));
l.Add(new DirectoryInfo(@"C:UsersPublicDownloads"));
var c = l.RecursionEachSelect(f => f.GetDirectories(), f => f.GetDirectories().Length > 0);
MessageBox.Show(c.Count().ToString());
}
public static bool RegexIsMatch(this string s, string expression, System.Text.RegularExpressions.RegexOptions option)
public static bool RegexIsMatch(this string s, string expression)
public static System.Text.RegularExpressions.Match RegexMatch(this string s, string expression, System.Text.RegularExpressions.RegexOptions options)
public static System.Text.RegularExpressions.Match RegexMatch(this string s, string expression)
public static System.Text.RegularExpressions.MatchCollection RegexMatches(this string s, string expression, System.Text.RegularExpressions.RegexOptions options)
public static System.Text.RegularExpressions.MatchCollection RegexMatches(this string s, string expression)
public static string RegexReplace(this string s, string expression, string replacement value, System.Text.RegularExpressions.RegexOptions option)
public static string RegexReplace(this string s, string expression, string replacement value)
public static string[] RegexSplit(this string s, string expression, System.Text.RegularExpressions.RegexOptions options)
public static string[] RegexSplit(this string s, string expression)
Function: Commonly used regular expression function encapsulation, the usage method is the same as the Regex class.
public static T As<T>(this string s) where T : new(), general extension.SpecialString
public static universal extension.HtmlString AsHtmlString(this string s)
public static universal extension.PathString AsPathString(this string s)
public static universal extension.ServerPathString AsServerPathString(this string s)
public static universal extension.UriString AsUriString(this string s)
public static universal extension.XHtmlString AsXHtmlString(this string s)
public static universal extension.XmlString AsXmlString(this string s)
Function: Defined as a special type of string that can be further modified using unique formatting commands. (Currently, the subsequent formatting functions after definition are relatively limited and will be gradually added in the future)
example:
[TestMethod]
public void TestMethod15()
{
var s = @"C:abc";
var Out = @"C:abc1.exe";
Assert.AreEqual(Out, s.AsPathString().Combine(@"D:1.exe".AsPathString().FileName));
}
Conclusion These are the most frequently used extensions here, I hope they are equally useful to everyone:)
Download the extension method source code: http://www.uushare.com/user/icesee/file/2435046
Sample source code: http://www.uushare.com/user/icesee/file/2435063
XPS version of this article: http://www.uushare.com/user/icesee/file/2435098