Replace null value with another value in Linq using C# and VB.Net in ASP.Net

Last Reply 3 months ago By pandeyism

Posted 3 months ago

hello,

How to replace null values in linq

i have left join in linQ it works fine but when i call the column projectid which is null it gives error

how to type case null values in linQ

var q= (from pr in Profiles
        join projects in Projects on pr.ProfileID equals projects.ProfileID
        into rd
        from rt in rd.DefaultIfEmpty()
        select new {		 
	    pr.Profilename,
	    rt.ProjectName,
	    rt.ProjectId ? 0		 
        });

q.Dump();

 

Posted 3 months ago

Hi nauna,

Refer below sample.

HTML

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" />
        <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
        <asp:BoundField DataField="LastName" HeaderText="LastName" />
    </Columns>
</asp:GridView>

Namespaces

C#

using NorthwindModel;

VB.Net

Imports NorthwindModel

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        NorthwindEntities entity = new NorthwindEntities();
        var query = (from o in entity.Orders
                        join emp in entity.Employees
                        on o.EmployeeID equals emp.EmployeeID
                        into rd
                        from rt in rd.DefaultIfEmpty()
                        select new
                        {
                            EmployeeID = o != null ? (o.EmployeeID ?? 0) : 0,
                            FirstName = rt.FirstName,
                            LastName = rt.LastName
                        }).Take(5);
        GridView1.DataSource = query;
        GridView1.DataBind();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim entity As NorthwindEntities = New NorthwindEntities()
        Dim query = (From o In entity.Orders Group Join emp In entity.Employees On o.EmployeeID Equals emp.EmployeeID Into rd = Group From rt In rd.DefaultIfEmpty() Select New With {Key .EmployeeID = If(o IsNot Nothing, (If(o.EmployeeID, 0)), 0), Key .FirstName = rt.FirstName, Key .LastName = rt.LastName}).Take(5)
        GridView1.DataSource = query
        GridView1.DataBind()
    End If
End Sub

Screenshot