Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've written like a quad zillion extension methods, so here are a few ones I find particulary usefull. Feel free to implement.</p> <pre><code>public static class ControlExtenders { /// &lt;summary&gt; /// Advanced version of find control. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type of control to find.&lt;/typeparam&gt; /// &lt;param name="id"&gt;Control id to find.&lt;/param&gt; /// &lt;returns&gt;Control of given type.&lt;/returns&gt; /// &lt;remarks&gt; /// If the control with the given id is not found /// a new control instance of the given type is returned. /// &lt;/remarks&gt; public static T FindControl&lt;T&gt;(this Control control, string id) where T : Control { // User normal FindControl method to get the control Control _control = control.FindControl(id); // If control was found and is of the correct type we return it if (_control != null &amp;&amp; _control is T) { // Return new control return (T)_control; } // Create new control instance _control = (T)Activator.CreateInstance(typeof(T)); // Add control to source control so the // next it is found and the value can be // passed on itd, remember to hide it and // set an ID so it can be found next time if (!(_control is ExtenderControlBase)) { _control.Visible = false; } _control.ID = id; control.Controls.Add(_control); // Use reflection to create a new instance of the control return (T)_control; } } public static class GenericListExtenders { /// &lt;summary&gt; /// Sorts a generic list by items properties. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type of collection.&lt;/typeparam&gt; /// &lt;param name="list"&gt;Generic list.&lt;/param&gt; /// &lt;param name="fieldName"&gt;Field to sort data on.&lt;/param&gt; /// &lt;param name="sortDirection"&gt;Sort direction.&lt;/param&gt; /// &lt;remarks&gt; /// Use this method when a dinamyc sort field is requiered. If the /// sorting field is known manual sorting might improve performance. /// &lt;/remarks&gt; public static void SortObjects&lt;T&gt;(this List&lt;T&gt; list, string fieldName, SortDirection sortDirection) { PropertyInfo propInfo = typeof(T).GetProperty(fieldName); if (propInfo != null) { Comparison&lt;T&gt; compare = delegate(T a, T b) { bool asc = sortDirection == SortDirection.Ascending; object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null); object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null); return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0; }; list.Sort(compare); } } /// &lt;summary&gt; /// Creates a pagged collection from generic list. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type of collection.&lt;/typeparam&gt; /// &lt;param name="list"&gt;Generic list.&lt;/param&gt; /// &lt;param name="sortField"&gt;Field to sort data on.&lt;/param&gt; /// &lt;param name="sortDirection"&gt;Sort direction.&lt;/param&gt; /// &lt;param name="from"&gt;Page from item index.&lt;/param&gt; /// &lt;param name="to"&gt;Page to item index.&lt;/param&gt; /// &lt;param name="copy"&gt;Creates a copy and returns a new list instead of changing the current one.&lt;/param&gt; /// &lt;returns&gt;Pagged list collection.&lt;/returns&gt; public static List&lt;T&gt; Page&lt;T&gt;(this List&lt;T&gt; list, string sortField, bool sortDirection, int from, int to, bool copy) { List&lt;T&gt; _pageList = new List&lt;T&gt;(); // Copy list if (copy) { T[] _arrList = new T[list.Count]; list.CopyTo(_arrList); _pageList = new List&lt;T&gt;(_arrList); } else { _pageList = list; } // Make sure there are enough items in the list if (from &gt; _pageList.Count) { int diff = Math.Abs(from - to); from = _pageList.Count - diff; } if (to &gt; _pageList.Count) { to = _pageList.Count; } // Sort items if (!string.IsNullOrEmpty(sortField)) { SortDirection sortDir = SortDirection.Descending; if (!sortDirection) sortDir = SortDirection.Ascending; _pageList.SortObjects(sortField, sortDir); } // Calculate max number of items per page int count = to - from; if (from + count &gt; _pageList.Count) count -= (from + count) - _pageList.Count; // Get max number of items per page T[] pagged = new T[count]; _pageList.CopyTo(from, pagged, 0, count); // Return pagged items return new List&lt;T&gt;(pagged); } /// &lt;summary&gt; /// Shuffle's list items. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;List type.&lt;/typeparam&gt; /// &lt;param name="list"&gt;Generic list.&lt;/param&gt; public static void Shuffle&lt;T&gt;(this List&lt;T&gt; list) { Random rng = new Random(); for (int i = list.Count - 1; i &gt; 0; i--) { int swapIndex = rng.Next(i + 1); if (swapIndex != i) { T tmp = list[swapIndex]; list[swapIndex] = list[i]; list[i] = tmp; } } } /// &lt;summary&gt; /// Converts generic List to DataTable. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;Type.&lt;/typeparam&gt; /// &lt;param name="list"&gt;Generic list.&lt;/param&gt; /// &lt;param name="columns"&gt;Name of the columns to copy to the DataTable.&lt;/param&gt; /// &lt;returns&gt;DataTable.&lt;/returns&gt; public static DataTable ToDataTable&lt;T&gt;(this List&lt;T&gt; list, string[] columns) { List&lt;string&gt; _columns = new List&lt;string&gt;(columns); DataTable dt = new DataTable(); foreach (PropertyInfo info in typeof(T).GetProperties()) { if (_columns.Contains(info.Name) || columns == null) { dt.Columns.Add(new DataColumn(info.Name, info.PropertyType)); } } foreach (T t in list) { DataRow row = dt.NewRow(); foreach (PropertyInfo info in typeof(T).GetProperties()) { if (_columns.Contains(info.Name) || columns == null) { row[info.Name] = info.GetValue(t, null); } } dt.Rows.Add(row); } return dt; } } public static class DateTimeExtenders { /// &lt;summary&gt; /// Returns number of month from a string representation. /// &lt;/summary&gt; /// &lt;returns&gt;Number of month.&lt;/returns&gt; public static int MonthToNumber(this DateTime datetime, string month) { month = month.ToLower(); for (int i = 1; i &lt;= 12; i++) { DateTime _dt = DateTime.Parse("1." + i + ".2000"); string _month = CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i).ToLower(); if (_month == month) { return i; } } return 0; } /// &lt;summary&gt; /// Returns month name from month number. /// &lt;/summary&gt; /// &lt;returns&gt;Name of month.&lt;/returns&gt; public static string MonthToName(this DateTime datetime, int month) { for (int i = 1; i &lt;= 12; i++) { if (i == month) { return CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(i); } } return ""; } } public static class ObjectExtender { public static object CloneBinary&lt;T&gt;(this T originalObject) { using (var stream = new System.IO.MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(stream, originalObject); stream.Position = 0; return (T)binaryFormatter.Deserialize(stream); } } public static object CloneObject(this object obj) { using (MemoryStream memStream = new MemoryStream()) { BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone)); binaryFormatter.Serialize(memStream, obj); memStream.Position = 0; return binaryFormatter.Deserialize(memStream); } } } public static class StringExtenders { /// &lt;summary&gt; /// Returns string as unit. /// &lt;/summary&gt; /// &lt;param name="value"&gt;Value.&lt;/param&gt; /// &lt;returns&gt;Unit&lt;/returns&gt; public static Unit ToUnit(this string value) { // Return empty unit if (string.IsNullOrEmpty(value)) return Unit.Empty; // Trim value value = value.Trim(); // Return pixel unit if (value.EndsWith("px")) { // Set unit type string _int = value.Replace("px", ""); // Try parsing to int double _val = 0; if (!double.TryParse(_int, out _val)) { // Invalid value return Unit.Empty; } // Return unit return new Unit(_val, UnitType.Pixel); } // Return percent unit if (value.EndsWith("%")) { // Set unit type string _int = value.Replace("%", ""); // Try parsing to int double _val = 0; if (!double.TryParse(_int, out _val)) { // Invalid value return Unit.Empty; } // Return unit return new Unit(_val, UnitType.Percentage); } // No match found return new Unit(); } /// &lt;summary&gt; /// Returns alternative string if current string is null or empty. /// &lt;/summary&gt; /// &lt;param name="str"&gt;&lt;/param&gt; /// &lt;param name="alternative"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static string Alternative(this string str, string alternative) { if (string.IsNullOrEmpty(str)) return alternative; return str; } /// &lt;summary&gt; /// Removes all HTML tags from string. /// &lt;/summary&gt; /// &lt;param name="html"&gt;String containing HTML tags.&lt;/param&gt; /// &lt;returns&gt;String with no HTML tags.&lt;/returns&gt; public static string StripHTML(this string html) { string nohtml = Regex.Replace(html, "&lt;(.|\n)*?&gt;", ""); nohtml = nohtml.Replace("\r\n", "").Replace("\n", "").Replace("&amp;nbsp;", "").Trim(); return nohtml; } } </code></pre> <p>The first one is my favourite as it enables me to replace:</p> <pre><code>Control c = this.FindControl("tbName"); if (c != null) { // Do something with c customer.Name = ((TextBox)c).Text; } </code></pre> <p>With this:</p> <pre><code>TextBox c = this.FindControl&lt;TextBox&gt;("tbName"); customer.Name = c.Text; </code></pre> <p>Settings default string values:</p> <pre><code>string str = ""; if (string.IsNullOrEmpty(str)) { str = "I'm empty!"; } </code></pre> <p>Becomes:</p> <pre><code>str = str.Alternative("I'm empty!"); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload