How to use Linq FirstOrDefault operator with condition
LinqFirstOrDefaultOperatorWithCondition.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 = { "Manzana velvet", "Naranjo dulce", "Lychee", "Naranja", "Lamyai", "Kathon" };
string firstOrDefaultFruitsItemStartsWithN = (from f in fruits
select f).FirstOrDefault(f => f.StartsWith("N"));
string firstOrDefaultFruitsItemStartsWithD = (from f in fruits
select f).FirstOrDefault(f => f.StartsWith("D"));
Label1.Text = "Fruits List: <br />";
foreach (string names in fruits)
{
Label1.Text += names.ToString() + "<br />";
}
Label2.Text = "After Calling FirstOrDefault Operator With Condition [StartsWith('N')]: " + firstOrDefaultFruitsItemStartsWithN;
Label2.Text += "<br /><br />After Calling FirstOrDefault Operator With Condition [StartsWith('D')]: " + firstOrDefaultFruitsItemStartsWithD;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to use Linq FirstOrDefault 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
<br /> FirstOrDefault With Condition
<br />How to get the first element of a sequence
<br /> or a default value if no element is found
</h2>
<hr width="500" align="left" color="CornFlowerBlue" />
<asp:Label
ID="Label1"
runat="server"
Font-Size="X-Large"
ForeColor="SaddleBrown"
Font-Italic="true"
>
</asp:Label>
<br />
<asp:Label
ID="Label2"
runat="server"
Font-Size="X-Large"
ForeColor="DodgerBlue"
Font-Italic="true"
>
</asp:Label>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
OnClick="Button1_Click"
Text="Test Linq Query Operator - FirstOrDefault"
Height="45"
Font-Bold="true"
ForeColor="DodgerBlue"
/>
</div>
</form>
</body>
</html>

- linq - Get first element of a sequence that match condition
- linq - How to get first element of a sequence or a default value
- linq - How to get the last element of a sequence
- linq - How to get last element of a sequence or a default value
- linq - Get last element of a sequence that match condition or a default value
- linq - How to take a given number of elements from a sequence
- linq - How to count occurrences of a string within a string
- linq - How to select distinct elements from a sequence
- LINQ to remove objects within a List
- linq - How to sort a date list order by ascending descending