Linq DefaultIfEmpty Operator - How to create a default element for an empty sequence
LinqDefaultIfEmptyOperator.aspx
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Import Namespace="System.Linq" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
string[] fruits = { "Lusho fruit", "Cambodian palm", "Chinesische Haselnuss", "Jambosa jambos", "Chinesische Jujube" };
var itemStartWithC = from f in fruits
where f.StartsWith("C")
select f;
var itemStartWithX = from f in fruits
where f.StartsWith("X")
select f;
Label1.Text = "Fruits List:....... <br />";
foreach (string names in fruits)
{
Label1.Text += names.ToString() + "<br />";
}
Label2.Text = "Fruits Start With(C):....... <br />";
foreach (string names in itemStartWithC.DefaultIfEmpty("Default Value"))
{
Label2.Text += names.ToString() + "<br />";
}
Label2.Text += "<br />Fruits Start With(X):....... <br />";
foreach (string names in itemStartWithX.DefaultIfEmpty("Default Value"))
{
Label2.Text += names.ToString() + "<br />";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Linq DefaultIfEmpty Operator - How to create a default element for an empty sequence</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Linq Standard Query Operator: Element Operator - DefaultIfEmpty
<br />How to create a default element for an empty sequence
</h2>
<hr width="600" align="left" color="CornFlowerBlue" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="X-Large"
ForeColor="SeaGreen"
Font-Italic="true"
>
</asp:Label>
<br />
<asp:Label
ID="Label2"
runat="server"
Font-Size="X-Large"
ForeColor="DarkMagenta"
Font-Italic="true"
>
</asp:Label>
<br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Linq Query Operator - DefaultIfEmpty"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>
- linq - How to sort elements of a sequence in ascending order
- How to use linq select query
- linq - How to get the sum of items in a numeric sequence
- linq - How to determine if any items in a sequence match condition
- linq - How to determine if a sequence contains a specific element
- linq - Get first element of a sequence that match condition
- linq - How to get first element of a sequence or a default value
- linq - Get a subset of elements from a sequence that match condition
- linq - How to concatenate two sequences
- linq - How to get element at a specified index or a default value