How to use Linq SingleOrDefault operator with condition
LinqSingleOrDefaultOperatorWithCondition.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 = { "Zoete sinaasappel", "Pyrus communis", "Sandoricum indicum", "Strawberry pear" };
var val = from f in fruits
select f;
Label1.Text = "Fruits List:....... <br />";
foreach (string names in fruits)
{
Label1.Text += names.ToString() + "<br />";
}
Label2.Text = "After Calling SingleOrDefault Operator With Condition [EndsWith('communis')]: " + val.SingleOrDefault(f => f.EndsWith("communis"));
Label2.Text += "<br /><br />After Calling SingleOrDefault Operator With Condition [EndsWith('false')]: " + val.SingleOrDefault(f => f.EndsWith("false"));
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to use Linq SingleOrDefault operator with condition</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:DarkBlue; font-style:italic;">
Linq Standard Query Operator: Element Operator - SingleOrDefault With Condition
<br />How to get the single element of a sequence or a
<br /> default value if no element is found
</h2>
<hr width="725" align="left" color="CornFlowerBlue" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="X-Large"
ForeColor="IndianRed"
Font-Italic="true"
>
</asp:Label>
<br />
<asp:Label
ID="Label2"
runat="server"
Font-Size="X-Large"
ForeColor="CornflowerBlue"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Linq Query Operator - SingleOrDefault"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>

- linq - How to sort elements of a sequence in ascending order
- linq - How to determine if any items in a sequence match condition
- linq - How to get a sequence that skips a given number of items
- linq - Get first element of a sequence that match condition
- linq - How to get last element of a sequence that match condition
- linq - Get a subset of elements from a sequence that match condition
- linq - How to generate a list with a specific range of numbers
- linq - How to get single element of a sequence that match condition
- linq - How to get single element of a sequence or a default value
- linq - How to cast elements of a sequence to a given data type