Get (Retrieve) first record in list from Linq query using C# and VB.Net in ASP.Net

nauna
 
on Dec 05, 2019 11:21 PM
2680 Views

hello,

i have this linQ query, i want to get first row productid from this query

int productid=q.productid (do not know how to get first row )

var q=(from d in db.Product_Description
       where d.ProductGUID==Id
       orderby d.DescriptionName
       select d);
Download FREE API for Word, Excel and PDF in ASP.Net: Download
arunkurmi
 
on Dec 06, 2019 02:09 AM

Hi nauna,

For selecting n-number of row use Take() method.

Check this example. now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="CustomerID" HeaderText="ID" />
        <asp:BoundField DataField="ContactName" HeaderText="Name" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Linq;
using NorthwindModel;

VB.Net

Imports System.Linq
Imports NorthwindModel

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}

protected void BindGrid()
{
    using (NorthwindEntities entities = new NorthwindEntities())
    {
        var result = (from customer in entities.Customers
                        orderby customer.ContactName
                        select customer).Take(1);
        this.gvCustomers.DataSource = result;
        this.gvCustomers.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
    End If
End Sub

Protected Sub BindGrid()
    Using entities As NorthwindEntities = New NorthwindEntities()
        Dim result = (From customer In entities.Customers
                      Order By customer.ContactName
                      Select customer).Take(1)
        Me.gvCustomers.DataSource = result
        Me.gvCustomers.DataBind()
    End Using
End Sub

Output

IDNameCountry
ROMEY Alejandra Camino Spain