Linq LastOrDefault Operator - How to get the last element of a sequence or a default value if no element is found
LinqLastOrDefaultOperator.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Linq" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
string[] fruits = { "Litchibaum", "Litschipflaume", "Mangistan", "Manzana", "Matum", "Malay apple" };
string[] emptyArray = {};
string lastOrDefaultFruitsItem = (from f in fruits
select f).LastOrDefault();
string lastOrDefaultEmptyArrayItem = (from f in emptyArray
select f).LastOrDefault();
Label1.Text = "Fruits List: <br />";
foreach (string names in fruits)
{
Label1.Text += names.ToString() + "<br />";
}
Label2.Text = "After Calling LastOrDefault Operator [fruits]: " + lastOrDefaultFruitsItem;
Label2.Text += "<br /><br />After Calling LastOrDefault Operator [emptyArray]: " + lastOrDefaultEmptyArrayItem;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Linq LastOrDefault Operator - How to get the last element of a sequence or a default value if no element is found</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Linq Standard Query Operator: Element Operator - LastOrDefault
<br />How to get the last element of a sequence or
<br /> a default value if no element is found
</h2>
<hr width="550" align="left" color="CornFlowerBlue" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="X-Large"
ForeColor="DarkSeaGreen"
Font-Italic="true"
>
</asp:Label>
<br />
<asp:Label
ID="Label2"
runat="server"
Font-Size="X-Large"
ForeColor="DarkBlue"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Linq Query Operator - LastOrDefault"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>