In: Computer Science
C# ( asp.net ) 2019 visual studio
I have a dropdown option. If I choose "date" option, I get to enter list of dates like 02/08/1990, 06/14/1890 in (mm/dd/YYYY) format.
How can I sort these dates in ascending order?. Can you provide me some code. Thank you
There are so many ways to sort the date field in the dropdown. Method 1: --------- you can simply write the query using "ORDER BY" in your code it self. select * from [table name] order by convert(nvarchar,DateValidFrom,103)
Method 2 :
-------------
For this syntax first you need to add the namespace otherwise you will face an issue.Which is,
[add namespace using System.Linq;]
Syntax: var orderedDateList = date.OrderBy(x => DateTime.Parse(x)).ToList();
Here 'var' can accept any type of variable.
Method 3:
--------------
Here i am just providing an example for understanding.
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
List<DateTime> holidays = new List<DateTime>();
DateTime today = DateTime.Today; holidays.Add(today);
holidays.Add(today.AddDays(5));
holidays.Add(today.AddDays(1));
holidays.Add(today.AddDays(7));
holidays.Add(today.AddDays(3));
Label1.Text = "holidays.....<br /> ";
foreach (DateTime d in holidays)
{
Label1.Text += d.ToShortDateString() + "<br />";
}
var sortedholidays = holidays.OrderBy(x => x);
Label1.Text += "<br />ascending sorted holidays.........<br />";
foreach (DateTime d in sortedholidays)
{
Label1.Text += d.ToShortDateString() + "<br />";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>c# linq example - sort date List order by ascending descending</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;"> c# example - sort date List order <br /> by ascending and descending </h2> <hr width="550" align="left" color="LightBlue" />
<asp:Label ID="Label1" runat="server" Font-Size="Large" >
</asp:Label> <br />
<asp:Button ID="Button1" runat="server" Text="sort date List" OnClick="Button1_Click" Height="40" Font-Bold="true" /> </div>
</form>
</body>
</html>
Method 1 is very easy process to solve your problem. As i do not know your exact code here i am providing a simple example.