Explain C# Sort String

You need to sort your List or array of strings using the C# programming language. You have a small or medium number of strings, meaning you don't need to deal with edge cases. The C# language and .NET Framework has several collection sorting methods and also there is LINQ query syntax. This document benchmarks and demonstrates the sort methods, such as Array.Sort.

Example string arrays

Here we see the example string[] array that you have in your C# program. The name "Zimbabwe" comes after the name "America", so the output array must be ordered with America first and finally Zimbabwe.
Unsorted

Zimbabwe
America
India
Germany
China
Ukraine

Sorted

America
China
India
Germany
Ukraine
Zimbabwe

Sort in place

Here we see how you can call the static Array.Sort method and use it to sort a string array in place. The result is an alphabetical sort. This console program demonstrates how to use the Array.Sort method.
Program that uses Array.Sort [C#]

using System;

class Program
{
    static void Main()
    {
 string[] a = new string[]
 {
     "Egyptian",
     "Indian",
     "American",
     "Chinese",
     "Filipino",
 };
 Array.Sort(a);
 foreach (string s in a)
 {
     Console.WriteLine(s);
 }
    }
}

Output

American
Chinese
Egyptian
Filipino
Indian

Sort strings with LINQ

Here we see how to take a string[] array and use a LINQ query expression to order its contents alphabetically. Note that we are ordering the strings, not the letters in the strings. You can see that the orderby keyword results in the same output as the Array.Sort method.
Program that uses LINQ [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
 string[] a = new string[]
 {
     "Indonesian",
     "Korean",
     "Japanese",
     "English",
     "German"
 };
 var sort = from s in a
     orderby s
     select s;

 foreach (string c in sort)
 {
     Console.WriteLine(c);
 }
    }
}

Output

English
German
Indonesian
Japanese
Korean
Note on the example code. When you use the query expression in LINQ, it returns an IEnumerable collection. This just means it is a collection that you have to enumerate (loop over) to get.

Sort strings in reverse (LINQ)

Here we sort strings from Z-A instead of from A-Z. This is called reverse alphabetic order. LINQ here is used with a query expression that is an enumeration of the original strings ordered from Z-A.
Program that uses LINQ descending [C#]

using System;
using System.Linq;

class Program
{
    static void Main()
    {
 string[] a = new string[]
 {
     "French",
     "Italian",
     "European",
     "Irish",
     "Vietnamese"
 };
 var desc = from s in a
     orderby s descending
     select s;

 foreach (string c in desc)
 {
     Console.WriteLine(c);
 }
    }
}

Output

Vietnamese
Italian
Irish
French
European
Description. This example is the same as in the previous example, except use different strings, and uses the descending keyword. Ascending means to go from lowest to highest (A-Z), while descending means to go from highest to lowest (Z-A). You can find more information on the descending contextual keyword.
Ascending KeywordDescending Keyword

Sort List

List<string> indicates a generic List collection of strings. Internally, it is stored as an array, but it is not an array type in the C# language. Therefore, you have to use its separate Sort method. Also, you can use LINQ with the exact syntax on List as used on arrays. This is because both arrays and Lists implement the IEnumerable interface.
Sort List Method
Program that uses List [C#]

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
 List<string> l = new List<string>()
 {
     "Australian",
     "Mongolian",
     "Russian",
     "Austrian",
     "Brazilian"
 };
 l.Sort();
 foreach (string s in l)
 {
     Console.WriteLine(s);
 }
    }
}

Output

Australian
Austrian
Brazilian
Mongolian
Russian
Tip

Review

We can look at what MSDN and other sites say about the sort methods I showed in the examples. I reference MSDN as well as other articles on Dot Net Perls.
Array.Sort. This method sorts the elements in the received array. It uses the IComparable interface implementation IComparable uses the CompareTo method.
IComparable Example With CompareToArray.Sort Examplemsdn.microsoft.comList(T).Sort. This is a generic class method. It must have its type specified at compile-time. It can receive a delegate method, which is not covered in this article. MSDN: "This method uses Array.Sort which uses the QuickSort algorithm." This means this method is equivalent to Array.Sort.
msdn.microsoft.comOrderby, ascending, descending. The orderby keyword is not a method per se. It compiles into a method call. It is query expression syntax in LINQ. See the linked article for more information.
OrderBy ClauseLINQ Methods

Different Sort methods

Here we see the three ascending sort methods in the first part of this document together. Each of these three methods returns a copy of the array in sorted form. They all copy first, then sort. The program can be run directly in a new Visual Studio console application.
Program that shows different sort methods [C#]

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
 string[] a = new string[]
 {
     "Salvadorian",
     "Kenyan",
     "Rwandan",
     "Icelandic",
     "African"
 };
 string[] b = SortArray(a);            // b is sorted
 string[] c = SortLinq(a);             // c is sorted

 List<string> l = new List<string>(a);
 List<string> d = SortList(l);         // d is sorted
    }

    static string[] SortArray(string[] a)
    {
 string[] res = (string[])a.Clone();
 Array.Sort(res);
 return res;
    }

    static string[] SortLinq(string[] a)
    {
 var res = from item in a
    orderby item ascending
    select item;
 return res.ToArray();
    }

    static List<string> SortList(List<string> l)
    {
 List<string> res = new List<string>(l);
 res.Sort();
 return res;
    }
}
First method. The first sorting method, named SortArray, demonstrates the use of Clone to make a shallow copy of the parameter array. In SortArray, the string[] method variable is pushed onto the stack and it is then sorted with Array.Sort.
Second method. In the second method, called SortLinq, we use the LINQ query syntax to get an IEnumerable collection of the parameter string[] array that is ordered from A-Z. It then uses ToArray() to evaluate the IEnumerable collection and return. More information is available on the ToArray extension method.
ToArray Extension MethodThird method. The third method, named SortList, receives a List parameter and then calls the List sort method on it. Because List.Sort internally uses Array.Sort, the performance is almost the same. This method copies before sorting.
Sort string debugger screenshot

String array initializer syntax

In the C# language, there are several different syntaxes for instantiating a string[] array. They are normally equivalent in performance, and just vary in appearance. Here we look at the syntax differences in a complete example program.
String Array
String array initializer examples [C#]

class Program
{
    static void Main()
    {
 string[] a = new string[]
 {
     "French",
     "Spanish",
     "Canadian",
     "Mexican",
     "Swedish",
 };
 string[] b =
 {
     "Polish",
     "Israeli",
     "Turkish",
     "Pakistani",
     "Belgian",
 };
 var c = new string[]
 {
     "Iraqi",
     "Iranian",
     "Romanian",
     "Latvian",
     "Norwegian",
 };
    }
}
Note on the three examples. The three local variables above all are string[5] collections, and their syntaxes can all be used interchangeably. Your preferences and your team's guidelines will be important here.

Benchmarks

Here we see that the three helper methods that copy and then sort an array parameter are very close in performance. Next I compare the three methods on arrays of 46, 92, and 460 elements.
Array sorting method [C#]

static string[] SortArray(string[] a)
{
    string[] res = (string[])a.Clone();
    Array.Sort(res);
    return res;
}

LINQ sorting method [C#]

static string[] SortLinq(string[] a)
{
    var res = from item in a
       orderby item ascending
       select item;
    return res.ToArray();
}

List sorting method [C#]

static List<string> SortList(List<string> l)
{
    List<string> res = new List<string>(l);
    res.Sort();
    return res;
}

Benchmark results, 46 strings

Array method: 400 ms
LINQ method:  410 ms
List method:  406 ms

Benchmark results, 92 strings

Array method: 2220 ms
LINQ method:  2290 ms
List method:  2205 ms

Benchmark results, 460 strings

Array method: 14504 ms
LINQ method:  15100 ms
List method:  14350 ms
Interpretation of the results. What I found is that the three methods shown are very similar in performance. In your program, you will need to benchmark them when fine-tuning your own algorithm. We cannot make many generalizations from this experiment.
.NET Framework illustration

Internal sorting routines

Internally, you can see that the List sort method is implemented with Array.Sort. This is why is performs very closely to how the Array.Sort method does. To examine the internals of the List sorting method, you can open IL Disassembler and click on the Sort call.
IL Disassembler Tutorial
Part of implementation of List.Sort [C#]

Array.Sort<T>(this._items, index, count, comparer);
Type specifier. The Array.Sort method shown is a generic method, which means you must specify the type when you call the method. Note that the C# compiler can derive the type implicitly in many cases. This means that Array.Sort is the same as Array.Sort<T>.

Summary

We saw some examples of how to sort strings in the C# programming language, along with a simple benchmark that includes copying of the collections. Be careful to copy your collection first if you don't want to replace it with the sorted instance. We learned that the List sort method and the Array.Sort method are implemented with the same algorithm.

Mask Edit Extender Breafly


MaskedEditExtender Properties:


Mask Type: This is the main property in mask edit extender based on the mask type validation is performed.
Mask Type have four main validations except none
None: No validations
Number: It is validate user entered only number in the textbox
Date: It is validate user entered correct date in the textbox.
Time: Time is validate user enter correct format of time in the textbox.
DateTime: DateTime is used to validate user entered valid date and time
Mask: This property is used to denote what is the characters user to be entered in the textbox and specify separator.

MaskedEditValidator Properties:


ControlToValidate: Entered here which textbox you want to validate
ControlExtender:: Entered here which maskededitextender is control in that textbox.
IsValidEmpty: If your textbox is mandatory then set this property as true.
MaximumValue: This property is used to set maxmimum value of that masked textbox.
Minimum Value: This property is used to set Minimum value of that textbox
ValidationExpression: It is used to validate textbox using regular expression
TooltipMessage: This property is used to show tooltip of the texbox.
EmptyValueMessage: This property is used to show error when textbox is empty
InvalidValueMessage: This property is show error when user enter wrong date etc. in that textbox
InvalidValueBlurredMessage: This property is show error message after user leave from textbox only entered value is invalid.
MaximumValueBlurredMessage: This property is show error message when user entered out of maxmimum value in the textbox.
MinimumValueBlurredText: This property is show error message if user entered minimum values compared to specified minimum value.

Symbol and Description

9   Allow only numeric in that position of the textbox
L   Allow only letter in that position of the textbox
$   Allow only a letter or a space
C   Allow only a custom character. It is case sensitive.
A   Allow only a letter or a custom character
N   Allow only a numeric or custom character
?   Allow any character user to be entered in the textbox
/   This one is used to denote date separator
:   This one is used to denote time separator
.   This one is used to denote decimal separator
,   This one is used to denote thousand separator
\   This one is escape character to separate values ex .999\/999 if we use like this / is appear in between six numbers

Client side:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>AJAX Masked Edit Extender and Masked Edit Validator</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
        <table cellpadding="0" cellspacing="0" align="center" width="1000">
            <tr>
                <td height="40" colspan="2">
                    <b>
                        <h3>AJAX Masked Edit Extender and Masked Edit Validator Examples</h3>
                    </b>
                </td>
            </tr>
            <tr>
                <td height="40" width="50%">
                    Enter Number to test
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" Width="180"></asp:TextBox>
                    <asp:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="TextBox1"
                        Mask="9,99,999.99" MessageValidatorTip="true" MaskType="Number" InputDirection="RightToLeft"
                        AcceptNegative="Left" ErrorTooltipEnabled="True" />
                    <asp:MaskedEditValidator ID="MaskedEditValidator1" runat="server" ControlExtender="MaskedEditExtender1"
                        ControlToValidate="TextBox1" IsValidEmpty="false" MaximumValue="100000" MinimumValue="-100"
                        EmptyValueMessage="Enter Some Numbers" MaximumValueMessage="Number must be less than 1,00,000"
                        MinimumValueMessage="Number must be greater than -100" EmptyValueBlurredText="*"
                        ToolTip="Enter values from -100 to 1,00,000"></asp:MaskedEditValidator>
                </td>
            </tr>
            <tr>
                <td height="40">
                    Enter Time to test (HH:mm:ss)
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="180"></asp:TextBox>
                    <asp:MaskedEditExtender ID="MaskedEditExtender2" runat="server" TargetControlID="TextBox2"
                        Mask="99:99:99" MessageValidatorTip="true" MaskType="Time" InputDirection="RightToLeft"
                        ErrorTooltipEnabled="True" />
                    <asp:MaskedEditValidator ID="MaskedEditValidator2" runat="server" ControlExtender="MaskedEditExtender2"
                        ControlToValidate="TextBox2" IsValidEmpty="false" MaximumValue="23:59:59" MinimumValue="00:00:00"
                        EmptyValueMessage="Enter Time" MaximumValueMessage="23:59:59" InvalidValueBlurredMessage="Time is Invalid"
                        MinimumValueMessage="Time must be grater than 00:00:00" EmptyValueBlurredText="*"
                        ToolTip="Enter time between 00:00:00 to 23:59:59"></asp:MaskedEditValidator>
                </td>
            </tr>
            <tr>
                <td height="40">
                    Enter date to test (dd/MM/yyyy)
                </td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server" Width="180"></asp:TextBox>
                    <asp:MaskedEditExtender ID="MaskedEditExtender3" runat="server" TargetControlID="TextBox3"
                        Mask="99/99/9999" MessageValidatorTip="true" MaskType="Date" InputDirection="RightToLeft"
                        ErrorTooltipEnabled="True" />
                    <asp:MaskedEditValidator ID="MaskedEditValidator3" runat="server" ControlExtender="MaskedEditExtender3"
                        ControlToValidate="TextBox3" IsValidEmpty="false" MaximumValue="01/01/2099" MinimumValue="01/01/2000"
                        EmptyValueMessage="Enter Date Value" MaximumValueMessage="Date must be less than 01/01/2099"
                        InvalidValueBlurredMessage="Date is invalid" MinimumValueMessage="Date must be grater than 01/01/2000"
                        EmptyValueBlurredText="*" ToolTip="Enter date between 01/01/2000 to 01/01/2099"></asp:MaskedEditValidator>
                </td>
            </tr>            
            <tr>
                <td height="40" colspan="2" align="center">
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html> 

Dynamically Paging for First, Next, Previous and Last in gridview

From this Article you can know how make Paging for First, Next, Previous and Last in GridView.


1) First  fill the gridview with Data from a Table.
2) Drag and Drop 4 Buttons keep it at the bottom of the Gridview.
3) Change the text of a buttons using Properties.
4) Select Gridview Properties and set AllowPaging=True. See the below picture



5) Expand the PageSetting Properties of Gridview, and set visible property as False.
6) Next we have to set a gridview PageSize property. The Default
   PageSize is 10.you can keep how  much size you want to display rows per page.
   Here I kept 6 rows to display in gridview per page. You can observe how to set
  page in ‘Pagesetting Picture’ marked with yellow color...


7) Under SelectedRowStyle set ‘ShowFooter as False’
8) The Ouptput of your gridview Image is shown below.

      How to Write the Code for Paging First, Next, Previous and Last.
1)     Paging for First Button: Double click on ‘First’ Button and write the below code.

     protected void btnfirst_Click(object sender, EventArgs e)
        {
        gridview1.PageIndex = 0;
     }


Explantion: when you run the Page it contains 6 recors in Gridview.
Suppose the user in last Page.When the user clicks  on ‘First Button’ first 6 records of the page has to be display in gridview.so the first gridview page Index(property) is ‘zero’.There is a Property called ‘PageIndex’ for Gridview.

2)      Paging for Next Button: Double click on ‘Next Button ‘and write the below code.

   protected void btnnext_Click(object sender, EventArgs e)
    {
         int i = gridview1.PageIndex + 1;
            if (i <= gridview1.PageCount)
            {
                gridview1.PageIndex = i;
         }
}
Explanation: ’PageCount’ is used to count number of pages availble in a Gridview.

3)     Paging for Previous Button: Double click on ‘Previous Button‘and write the below code.

       protected void btnprevious_Click(object sender, EventArgs e)
     {
            int i = gridview1.PageCount;

              if (gridview1.PageIndex > 0)
              {

                gridview1.PageIndex = gridview1.PageIndex - 1;
               
               }
       }


4)     Paging for Last Button: Double click on ‘Last Button‘and write the below code/

   protected void btnlast_Click(object sender, EventArgs e)
    {
      
            gridview1.PageIndex = gridview1.PageCount;
}


In the Above Picture observe on Last Button.it is in Enable=False state,because in gridview the last page records are displaying.So again no need with last Button.In same Senario remaining buttons also made Enable=False where the buttons are not usefull to click the user.you can see the coding fo Enable in .aspx.cs page

The Complete .aspx.cs Page
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        btnfirst.Enabled = false;
        btnprevious.Enabled = false;
    }
protected void btnnext_Click(object sender, EventArgs e)
    {
       
            int i = gridview1.PageIndex + 1;
            if (i <= gridview1.PageCount)
            {
                gridview1.PageIndex = i;
                btnlast.Enabled = true;
                btnprevious.Enabled = true;
                btnfirst.Enabled = true;
            }
          
            if (gridview1.PageCount-1 == gridview1.PageIndex)
            {
                btnnext.Enabled = false;
                btnlast.Enabled = false;
            }
          
           
    }
    protected void btnprevious_Click(object sender, EventArgs e)
    {
      
            int i = gridview1.PageCount;
            if (gridview1.PageIndex > 0)
            {
                gridview1.PageIndex = gridview1.PageIndex - 1;
                btnlast.Enabled = true ;
            }
            if (gridview1.PageIndex == 0)
            {
                btnfirst.Enabled = false;
            }
            if (gridview1.PageCount - 1 == gridview1.PageIndex+1)
            {
                btnnext.Enabled = true;
            }
            if (gridview1.PageIndex == 0)
            {
                btnprevious.Enabled = false;
            }
    }
    protected void btnlast_Click(object sender, EventArgs e)
    {
      
            gridview1.PageIndex = gridview1.PageCount;
            btnlast.Enabled = false;
            btnfirst.Enabled = true;
    }
    protected void btnfirst_Click(object sender, EventArgs e)
    {
        gridview1.PageIndex = 0;
        btnfirst.Enabled = false;
        btnprevious.Enabled = false;
        btnlast.Enabled = true;
        btnnext.Enabled = true;
       
    }
}