Reader Level:
Article

Play With First ()/FirstOrDefault () or Single ()/SingleOrDefault () in LINQ

By Vijay Prativadi on Nov 18, 2012
Today, in this article let’s play around with one of the interesting and most useful concepts in LINQ.

Introduction

Today, in this article let's play around with one of the interesting and most useful concepts in LINQ.

Question: What are these?

Please refer to the following table:

LINQoperation1.png

Step 1: Create a new WebForm project

LINQoperation2.png

Step 2: The complete code of WebForm1.aspx looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="FirstandSingleLINQApp.WebForm1" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <style type="text/css">
        .grid
        {
            margin-top: 50px;
        }
    </style
>
    <title></title>
</head>
<
body>
    <form id="form1" runat="server">
    <center>
        <div>
            <table>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Label ID="Label1" runat="server" Text="Play with First/FirstOrDefault or Single/SingleOrDefault using LINQ"
                            Font-Bold="true" Font-Size="Large" Font-Names="Verdana" ForeColor="Maroon"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="Button1" runat="server" Text="First()" Font-Names="Verdana" Width="213px"
                            BackColor="Orange" Font-Bold="True" OnClick="Button1_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="Button2" runat="server" Text="FirstOrDefault()" Font-Names="Verdana"
                            Width="213px" BackColor="Orange" Font-Bold="True" OnClick="Button2_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="Button3" runat="server" Text="Single()" Font-Names="Verdana" Width="213px"
                            BackColor="Orange" Font-Bold="True" OnClick="Button3_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:Button ID="Button4" runat="server" Text="SingleOrDefault()" Font-Names="Verdana"
                            Width="213px" BackColor="Orange" Font-Bold="True" OnClick="Button4_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <asp:GridView ID="GridView1" runat="server" CssClass="grid" BackColor="LightGoldenrodYellow"
                            BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">
                            <AlternatingRowStyle BackColor="PaleGoldenrod" />
                            <FooterStyle BackColor="Tan" />
                            <HeaderStyle BackColor="Tan" Font-Bold="True" />
                            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                            <SortedAscendingCellStyle BackColor="#FAFAE7" />
                            <SortedAscendingHeaderStyle BackColor="#DAC09E" />
                            <SortedDescendingCellStyle BackColor="#E1DB9C" />
                            <SortedDescendingHeaderStyle BackColor="#C2A47B" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </center>
    </form>
</body>
</
html>

Step 3: The complete code of WebForm1.aspx.cs looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FirstandSingleLINQApp
{
    public partial class WebForm1 : System.Web.UI.
Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            var query = objEntities.Employee.First(); var querylist = new List<Employee> { query };
            GridView1.DataSource = querylist;
            GridView1.DataBind();
        }
        protected void Button2_Click(object sender, EventArgs e)|
        {
            var query = objEntities.Employee.FirstOrDefault();
            var querylist = new List<Employee> { query };
            GridView1.DataSource = querylist;
            GridView1.DataBind();
        }
        protected void Button3_Click(object sender, EventArgs e)
        {
            var query = objEntities.Employee.Single();
            var querylist = new List<Employee> { query };
            GridView1.DataSource = querylist;
            GridView1.DataBind();
        }
        protected void Button4_Click(object sender, EventArgs e)
        {
            var query = objEntities.Employee.Where(p => p.Age == 25).SingleOrDefault();
            var querylist = new List<Employee> { query };
            GridView1.DataSource = querylist;
            GridView1.DataBind();
        }
        #region Instance MembersCompanyEntities objEntities = new CompanyEntities();
        #endregion
    }
}

Step 4: The output of the application looks like this:

LINQoperation3.png

Step 5: The First () operation output of the application looks like this:

LINQoperation4.png

Step 6: The Single () operation output of the application looks like this (Here the sequence contains more than 1 element so throws up an exception):

LINQoperation5.png

I hope this article is useful for you. Look forward for your comments and feedback. Thanks Vijay Prativadi

Vijay Prativadi

Hey Everyone, It's Vijay. I am SDE mostly up on Microsoft Technologies. If you are thinking to know what I do mostly when I'm at work. I get a chance to work upon few Microsoft technologies. All the way along my core tec... Read more

COMMENT USING