在項目中很多時候都會對字符串和集合做特定的處理。而且很多地方都會去調用。為了解決這些問題。我們通常會在項目中吧這些方法提成公共方法。下面是自己總結的項目中用到的一些擴展方法。封裝成了一個Library放到github上.
https://github.com/FourLeafClover/LightWeight.Extensions
不多說我們來看看擴展的一些方法吧.
public static void Main(string[] args) { #region String Extensions string result0 = "[frank%loch".StringConvert4SQLLke(); //替換sql模糊匹配的時候里面的特殊字符
bool result1 = " abC".CurrentTrimEqualsIgnoreCase(" ABC "); // 比較兩字符串是否相同,忽略大小寫,字符串前后空白
List<string> result2 = "1-23@56*78".SplitByMutipleChar('-','@','*').ToList(); //多字母拆分字符串, 輸出 { 1 23 56 78 }的集合
bool result3 = "123".IsNullOrEmpty(); // 判斷字符串是否為null或者string.empty.
bool result4 = "123".IsLengthBetween(2, 4);
bool result5 = "123".IsShorterThan(2);
bool result6 = "123".IsLongerThan(2);
bool result7 = "You are the best".IsContainsAll("You", "the");// result==true,result8==false IsContainsAll 支持多參數輸入. 用于判斷字符串是否同時包含多個字符串 bool result8 = "You are the best".IsContainsAll("You", "123");
bool result9 = "You are the best".IsContainsAny("123", "the"); //result==true,result8==false IsContainsAll 支持多參數輸入. 用于判斷字符串是否包含多個字符串中的一個
bool result10 = "You are the best".IsContainsAny("sbc", "123");
string result11 = "frank".FirstCharToUpter();
string result12 = " frank ".RTrim(); // 去除字符串右邊的空白
string result13 = " frank ".LTrim(); // 去除字符串左邊空白
string result14 = new List<string>() { "frank", "loch", "hardy" }.ListToSqlIn(false); //用于sql里面的in(x,x,x)語句拼接 string result15 = new List<string>() { "1", "2", "3" }.ListToSqlIn(true); // result12 = "'frank','loch','hardy'",result12 = "1,2,3"
bool result16 = "frank".IsEqualsAnyOfThem("hardy", "frank"); // IsEqualsAnyOfItem支持多參數輸入,判斷字符串是否在多個刪除里面 #endregion #region ConvertExtensions // 用于string類型轉換int,decimal,datetime int result17 = "abc".TryToInt32(); int result18 = "123".TryToInt32(); decimal result19 = "1.3".TryToDecimal(); DateTime result20 = "2015/12/24".TryToDateTime(); #endregion #region ObjectExtensions Person p1 = new Person() { Name = "Frank" }; Person result21 = p1.DeepCopy<Person>(); // 深拷貝 #endregion #region List<string> lst = new List<string>() { "123", "456" }; bool result22 = lst.IsNullOrEmpty(); //判斷集合是否有內容 bool result23 = lst.CountGreaterThanZero(); List<Person> personList1 = new List<Person>() { new Person(){Name="Frank"}, new Person(){Name="Hardy"} }; List<Person> personList2 = new List<Person>() { new Person(){Name="Frank"}, new Person(){Name="Hardy"} };
///public static bool ObjectCollectionEquals<T>(this IEnumerable<T> collection1, IEnumerable<T> collection2, Func<T, T, bool> func),
/// func里面寫入兩個對象相同的方法.實現集合對象的比較 bool result24 = personList1.ObjectCollectionEquals(personList2, (val1, val2) => { return val1.Name != val2.Name; }); #endregion } [Serializable] public class Person { public string Name { get; set; } }
PS:代碼都很簡單. 就不剖析了. 各位博友誰還有比較常用的擴展方法都可以提出來. 我好更新到github上.這樣可以不斷的去完善這個library.
新聞熱點
疑難解答