Helper Functions

Helper Functions/ Extensions

AddIfNotNull collection extensions

I want to post a few recently created collection extensions to write in one line, what otherwise takes 2 or more public static void AddIfNotNull( this IList coll, T newItem) where T : class { if (newItem != null) { coll.Add(newItem); } } public static void AddRangeIfNotNullOrEmpty( this List coll, IEnumerable newItems) where T : class { if (!newItems.IsNullOrEmptySeq... { coll.AddRange(newItems); } } public static void AddIfNotContains( this Dictionary dictionary, TKey key, TValue value) { if ......

Helper method to Replace/Remove characters that do not match the Regular Expression

I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters. I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters. The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to ......

DataContractSerializer truncated string when used with MemoryStream,but works with StringWriter

We've used the following DataContractSerializeToXml method for a long time, but recently noticed, that it doesn't return full XML for a long object, but truncated it and returns XML string with the length of multiple-of-1024 , but the reminder is not included. internal static string DataContractSerializeToXml&... obj) { string strXml = ""; Type type= obj.GetType();//typeof(T) DataContractSerializer serializer = new DataContractSerializer(type); System.IO.MemoryStream aMemStr = new System.IO.MemoryStream(); ......

IsNullOrEmpty generic method for Array to avoid Re-Sharper warning

I’ve used the following extension method in many places. public static bool IsNullOrEmpty(this Object[] myArr) { return (myArr == null || myArr.Length == 0); }Recently I’ve noticed that Resharper shows warning covariant array conversion to object[] may cause an exception for the following codeObjectsOfMyClass.IsNull... resolved the issue by creating generic extension method public static bool IsNullOrEmpty<T>(this T[] myArr) { return (myArr == null || myArr.Length == 0); }Related ......

Case-insensitive Contains extension for list of strings

I wanted to have case-insensitive Contains method for list of strings.Overload Enumerable.Contains<TSou... Method (IEnumerable<TSource>, TSource, IEqualityComparer<TSourc... expects custom IEqualityComparer class.I was about to create my own class IgnoreCaseEqualityComparer : IEqualityComparer<string... then found StringComparer.Create Method, that allow to use standard class.public static bool ContainsString(this IEnumerable<string> collection, string toFind, bool ......