What is the difference between First() and FirstOrDefault()


Hi

Onetime i was giving interview then i got this question.Then i told both is used for same purpose. But it was not the exact answer.

In simple word, FirstOrDefault() will handle the exception but First() will not handle the exception.

First() and FirstOrDefault() are two extension methods of the Enumerable class.

So lets test with some example in asp.net

 protected void Page_Load(object sender, EventArgs e)
    {
      
        int[] number = { 1, 5, 6 };
        var num = number.Where(n => n > 10).FirstOrDefault();;
        Response.Write(num);

    }


Note: This code will not throws the exception. So if we have to handle the exception then we can use FirstOrDefault();.

Now lets test with First()

 protected void Page_Load(object sender, EventArgs e)
    {
      
        int[] number = { 1, 5, 6 };
        var num = number.Where(n => n > 10).First();
        Response.Write(num);

    }

Note: This code will throw the exception.

Advertisements
Posted in LINQ. 2 Comments »

How to fetch data on basis of multiple Id in LINQ or EF ?


Hi
Recently one of my project, there was requirement to filter from one table on basis of multiple Id. There was using EF. So in EF we can write the Syntax like this

using (DemoJobPortalModel.DemoJobPortalEntities objE = new DemoJobPortalModel.DemoJobPortalEntities())
{
List<int> ListCountryId = new List<int> { 3, 5, 7 };

var query = from m in objE.tblCountries
where ListCountryId.Contains(m.Id)
select m;
GridView1.DataSource = query;
GridView1.DataBind();
}

In Sql Server we can do like this

Select *from tblCountry where Id in (3,5,7)

How to insert data in XML file using LINQ to XML?


Step1:Create one class i.e Emp.cs and declare the property like this

public class Emp
{
public int Id { get; set; }
public string EmpName { get; set; }
public string EmpSal { get; set; }
}

Step2: Create the Emp.xml file like this in Solution Explore

<?xml version="1.0" encoding="utf-8"?>
<Emps>

</Emps>

Step3: Write the code in code behind like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

public partial class TestXml : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("Emp.xml"));

XElement newEmp = new XElement("Emp",
new XElement("EmpName", TextBox1.Text),
new XElement("EmpSal", TextBox2.Text)
);
newEmp.SetAttributeValue("Id", GetNextAvailableID());

data.Element("Emps").Add(newEmp);
data.Save(HttpContext.Current.Server.MapPath("Emp.xml"));

TextBox1.Text = "";
TextBox2.Text = "";

FillGrid();

}

private static int GetNextAvailableID()
{
XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("Emp.xml"));

return Convert.ToInt32(
(from c in data.Descendants("Emp")
orderby Convert.ToInt32(c.Attribute("Id").Value) descending
select c.Attribute("Id").Value).FirstOrDefault()
) + 1;
}

protected void FillGrid()
{
var query = from a in XElement.Load(MapPath("Emp.xml")).Elements("Emp")
select new Emp
{

Id = Convert.ToInt32(a.Attribute("Id").Value),
EmpName = (string)a.Element("EmpName"),
EmpSal = (string)a.Element("EmpSal")

};

GridView1.DataSource = query;
GridView1.DataBind();
}
}

Posted in LINQ, XML. 2 Comments »

Some useful Clauses and Methods of LINQ, Part #8


LINQ supports the following clauses that you can use in a query:

1. from—Enables you to specify the data source and a variable for iterating over the

data source (a range variable).

2.where—Enables you to filter the results of a query.

3.select—Enables you to specify the items included in the results of the query.

4.group—Enables you to group related values by a common key.

5.into—Enables you to store the results of a group or join into a temporary variable.

6.orderby—Enables you to order query results in ascending or descending order.

7.join—Enables you to join two data sources using a common key.

8.let—Enables you to create a temporary variable to represent subquery results.

List of some of the more interesting and useful methods  in LINQ:

. Aggregate()—Enables you to apply a function to every item in a sequence.

. Average()—Returns the average value of every item in a sequence.

. Count()—Returns the count of items from a sequence.

. Distinct()—Returns distinct items from a sequence.

. Max()—Returns the maximum value from a sequence.

. Min()—Returns the minimum value from a sequence.

. Select()—Returns certain items or properties from a sequence.

. Single()—Returns a single value from a sequence.

. Skip()—Enables you to skip a certain number of items in a sequence and return the remaining elements.

. Take()—Enables you to return a certain number of elements from a sequence.

. Where()—Enables you to filter the elements in a sequence.

LINQ To XML ? Part #4


What is the LINQ  To XML ?

It is the type of LINQ. Using Linq we can perform all basic operation with XML file.

I will show one of the easiest example

Step1: Create one XML file in asp.net project  like this

<?xml version=”1.0″ encoding=”utf-8″ ?>

<movies>

<movie>

<Title>Ghost </Title>

<Director>ABC</Director>

</movie>

<movie>

<Title>Forest </Title>

<Director>CDE</Director>

</movie>

<movie>

<Title>Water </Title>

<Director>EEE</Director>

</movie>

<movie>

<Title>Salt</Title>

<Director>WWW</Director>

</movie>

</movies>

Step2: Go to Solution Explorer, Right click on it and add a class “Movie.cs” .

You declare the property like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Movie
/// </summary>
public class Movie
{

public string Title { get; set; }
public string Director { get; set; }

}

Step3: Take one gridview Control  in design page

Step4: Add a namespace

using System.Xml.Linq;

Step5: Write the code in code behind page  like this

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

//var query = from a in

//                XElement.Load(MapPath(“Movie.xml”)).Elements(“movie”)

//            select a;

var query = from a in

XElement.Load(MapPath(“Movie.xml”)).Elements(“movie”)

select new Movie

{

Title = (string)a.Element(“Title”),

Director = (string)a.Element(“Director”)

};

GridView1.DataSource = query;

GridView1.DataBind();

}

}

Step6:You will get op like this

Posted in LINQ. 2 Comments »

LINQ to SQL ? Part #3


What is the LINQ to SQL?

This is one of the most useful and the easiest method to do database operation with sqlserver

  • Its all features located in System.Data.Linq
  • It also include basic object relation (O/R) mapper directly in Visual studio.
  • The O/R mapper enables you to quickly map sql-based datasource  to CLR object.

How to use LINQ to SQL ?

Steps1: Add a LINQ to SQL Class like this

Step2: Drag the Database table which one you are going to use.

Step3 : Save the page(Ctrl + s) where serialization mode=”Unidirectional”

like this image

Step4: Then In Design page, take one Gridview and Linqdatasource control and configure  the Linqdatasource control like this

Step5:  You will get op like this


Type of LINQ ? Part #2


Type of LINQ

There are 3 types of LINQ.

a. LINQ to Object

b. LINQ to XML

c. LINQ to SQL

LINQ to Object Example

It is used to perform complex query operation against any enumerable object

Example of LINQ to Object

Step1:Take a Gridview in aspx page.

Step2:Create a simple generic list of movie objects and bind with gridview like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

var movies = GetMovies();
var query = from m in movies
select m;

//Same result will give with this syntax
//var query = movies.Select(m => m);

//var query = from m in movies
// select new { m.Title, m.Director };

//var query = from m in movies
// select new {MovieTile= m.Title,Director= m.Director };

//var query = from m in movies
// orderby m.Title descending
// select new { movieTitle = m.Title, Director = m.Director };

//this syntax is used for filtering

//var query = from m in movies
// where m.Title == “Water” && m.Director == “WWW”
// select m;

GridView1.DataSource = query;
GridView1.DataBind();

}

public List<Movie> GetMovies()
{
return new List<Movie>
{
new Movie{Title="Gost",Director="ABC"},
new Movie{Title="Forest",Director="XYZ"},
new Movie{Title="Salt",Director="CDE"},
new Movie{Title="Water",Director="WWW"}
};
}

}

we will get o/p like this