Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts
Tuesday, October 22, 2013

Linq- AddRange Method in C#

In this post I’m going to explain you about Linq AddRange method. This method is quite useful when you want to add multiple elements to a end of list. Following is a method signature for this.
public void AddRange(
    IEnumerable<T> collection
)
To Understand let’s take simple example like following.

using System.Collections.Generic;
using System;
namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            foreach (var newname in newnames)
            {
                names.Add(newname);
            }
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I am adding content of array to a already created list via foreach loop. You can use AddRange method instead of for loop like following.It will same output as above.
using System;
using System.Collections.Generic;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames);
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Now when you run that example output is like following.

AddRangeLinqCsharp

Add Range in more complex scenario:

You can also use add range to more complex scenarios also like following.You can use other operator with add range as following.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames.Where(nn=>nn.StartsWith("Vi")));
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I have created array with string and filter it with where operator while adding it to an existing list. Following is output as expected.

AddRangeLinqCsharpAdvanceScneario

That’s it. Hope you like it. Stay tuned for more..
Share:
Thursday, June 27, 2013

Deferred vs Immediate execution in Linq

In this post, We are going to learn about Deferred vs Immediate execution in Linq.  There an interesting variations how Linq operators executes and in this post we are going to learn both Deferred execution and immediate execution.

What is Deferred Execution?


In the Deferred execution query will be executed and evaluated at the time of query variables usage. Let’s take an example to understand Deferred Execution better.
Share:
Thursday, May 23, 2013

How to sort a data table in C# with LINQ

One of friend today ask how we can sort data table based on particular column? So I thought it’s a good idea to write a blog post about it. In this blog post we learn how we can learn how we can sort database with LINQ queries without writing much more long code. So let’s write a code for that.

using System;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dataTable = CreateDataTalble();
            AddRowToDataTable(dataTable);
            Console.WriteLine("Before sorting");
            PrintDatable(dataTable);
            var Rows = (from row in dataTable.AsEnumerable()
                        orderby row["FirstName"] descending
                        select row);
            dataTable = Rows.AsDataView().ToTable();
            Console.WriteLine("==============================");
            Console.WriteLine("After sorting");
            PrintDatable(dataTable);
        }

        public static DataTable CreateDataTalble()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));
            return dt;
        }
        public static void AddRowToDataTable(DataTable dt)
        {
            dt.Rows.Add("Jalpesh", "Vadgama");
            dt.Rows.Add("Vishal", "Vadgama");
            dt.Rows.Add("Teerth", "Vadgama");
            dt.Rows.Add("Pravin", "Vadgama");
        }

        public static void PrintDatable(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                Console.WriteLine(string.Format("{0} {1}",
                    row[0], row[1]));
            }
        }
    }
}

Share:
Saturday, March 23, 2013

Difference between All and Any operator in linq

In this post we are going to learn about difference between ‘All’ and ‘Any’ operator in Linq.

Difference between ‘All’ and ‘Any’ operator:


All operator checks whether all elements have met specific conditions or not while Any operator check whether there is any elements exist in collection or not?

So what we are waiting for Let’s take a example.
using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = {1,2,3,4,5};
            bool result = intArray.All(i => i > 2);
            Console.WriteLine(result);
            result = intArray.Any();
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}
In the above example you can see that I have created an integer array and then checked with both all and any operator. In first condition I have checked that whether elements are greater then 2 or not and same way I have checked with any operator that its contains any element or not?

Now let’s run that example. To see how its works.
Share:
Saturday, March 16, 2013

All operator in linq

Few days back I came across “All” operator in Linq. I thought it will be good idea to write a blog post about it and share it with community.

All operator in linq:

It’s almost similar to select it returns all the element in the input sequence with matching condition in given predicate. Following is syntax for All.
public static bool All<TSource>( 
this IEnumerable<TSource> source, 
Func<TSource, bool> predicate)

It check the condition whether all the elements on collection matches given criteria and based on that it will return bool value.  It can be useful in scenario where we need to do some kind of validation whether all the elements of collection matches with certain condition or not.

So Let’s take a simple example. Following is a code for that.
using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = {1,2,3,4,5};
            bool result = intArray.All(i => i > 2);
            Console.WriteLine(result);
            result = intArray.All(i => i < 6);
            Console.WriteLine(result);
        }
    }
}

Share:
Wednesday, February 13, 2013

How to convert a list into array with Linq

In this post, I am going to explain how we can convert an generic list to simple int array with Help of Linq. Recently, I was working on an application and there I needed an Int array of for list of ids in generic list. I tried various methods and then with the help of ‘Select’ operator and ToArray method I have easily converted an generic list to the int array.

Lets take a simple example. I need a contact id list from a generic list of contacts and following is my contact class.

public class Contact
{
    public int ContactId { get; set; }
    public string Name { get; set; }
}

Now I have created a new GetContacts methods to create a new Generic List of Contacts.
Share:
Friday, February 1, 2013

SelectMany operator in Linq C#

SelectMany is an important operator in Linq. It takes each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. You can find out more information about different overload list from the below link.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

In this post I am going to explain How it can be really useful when you want to find list related to two entities. Practical example will be like a person can have multiple address and if you want to find list of addresses that are used with person then this SelectMany operator can be really useful.

So for this example First, I have create Address class with Street and Postalvcode property
public class Address
{
    public string Street { get; set; }
    public string PostalCode { get; set; }
}

Share:
Friday, January 18, 2013

Linq performance with Count() and Any()

Recently I was using resharper to refactor some of my code and found that it was suggesting to use any() extension method instead of count() method in List<T>. I was really keen about performance and found that resharper was right. There is huge performance difference between any() and count() if you are using count() just to check whether list is empty or not.

Difference between Count() and Any():


In Count() method code will traverse all the list and get total number of objects in list while in Any() will return after examining first element in the sequence. So in list where we have many object it will be significant execution time if we use count().
Share:
Friday, December 21, 2012

Where I can find SQL generated by Linq-To-SQL

Yesterday I have written a blog post about Where I can find SQL Generated by Entity Framework? and same day I got request from one of the our reader Ramesh that how I can find SQL generated by Linq-To-SQL?. I thought its a good idea to write a blog post to share amongst all who need this instead of reply in comments.  In this post I am going to explain how we can get SQL generated by Linq-To-SQL.

For this post I am going to use same table like following. A customer table with two columns CustomerId and CustomerName.

How to get SQL staement generated by Linq-To-SQL
Share:
Tuesday, April 17, 2012

Difference between SkipWhile and Where in linq

Before some time I have written a blog post about the SkipWhile operator and a reader of my blog asked me that we can do the same thing with Where also but there is a difference between this two. So In this post I am going to explain you difference between those two.

Where operator filters a list of collection based on condition. It will filter whole collection while SkipWhile will only skip those elements in list until condition is true and after that it will stop filtering of skipping.Now let’s take an example where we can see the difference between Where and SkipWhile. Following is a code for that.
Share:
Saturday, April 14, 2012

TakeWhile operator in linq

In this post I am going to explain TakeWhile Operator in details. TakeWhile is one of partitioning operator available in Linq. It will take sequence until condition becomes false.

Here is the example for that.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Linq
{
class Program
{
  static void Main(string[] args)
  {
      int[] numbers ={10,9,8,7,6,5,4,3,2,1};

      foreach(var number in numbers.TakeWhile(n=>n>5))
      {
          Console.WriteLine(number);
      }
  }
}
}


Share:

SkipWhile Method in Linq

I have been playing around linq and I have found great method call SkipWhile method. SkipWhile methods skips particular element which matches condition in predicate this can be use full in condition where we need to skip elements on particular condition.

So let’s take some example. I have written following console application code.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Linq
{
  class Program
  {
      static void Main(string[] args)
      {
          string[] names = { "Jalpesh", "Jayesh", "Tushar", "Tejas", "Sanjay", "Nijesh" };
          foreach(var name in names.SkipWhile(s=>s.ToLower().StartsWith("j")))
          {
              Console.WriteLine(name);
          }
      }
  }
}

Share:
Wednesday, August 17, 2011

Creating Basic RSS Reader in ASP.NET MVC 3

In this post I am going to explain you how we can create a basic RSS Reader with the help of Linq-To-Xml and ASP.NET MVC3 Razor. Those who are writing or reading Blogs already knows what is RSS Reader. But those who does not know What is RSS. Below is the definition for RSS as per Wikipedia.


RSS (originally RDF Site Summary, often dubbed Really Simple Syndication) is a family of web feed formats used to publish frequently updated works—such as blog entries, news headlines, audio, and video—in a standardized format.[2] An RSS document (which is called a "feed", "web feed",[3] or "channel") includes full or summarized text, plus metadata such as publishing dates and authorship.
 

You can find more information about RSS from the following links.

Now let’s start writing code creating a Basic RSS Reader. So first We need two things to create RSS Reader. A RSS Entity class which hold properties for RSS and Another method which populate IEnumerable of particular RSS Class. We are creating this example with ASP.NET So I have create One Model class called RSS Like following.
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class Rss
{
public string Link { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
}

Now our entity class is ready. Now we need a class and a method which will return IEnumerable of RSS Class. So I have created a Static Class RSS Reader which has “GetRSSFeed” Method which return RSS Feeds like following.

using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace CodeSimplified.Models
{
public class RssReader
{
private static string _blogURL = "http://feeds.feedburner.com/blogspot/DotNetJalps";
public static IEnumerable<Rss> GetRssFeed()
{

   XDocument feedXml = XDocument.Load(_blogURL);
   var feeds = from feed in feedXml.Descendants("item")
               select new Rss
               {
                   Title = feed.Element("title").Value,
                   Link = feed.Element("link").Value,
                   Description = Regex.Match(feed.Element("description").Value, @"^.{1,180}\b(?<!\s)").Value

               };

   return feeds;

}
}
}

As you can see in above code. I am loading RSS feed with XDcoument Class with my Blog RSS feed URL and Then I am populating RSS Class Enumerable with the help of the Linq-To-XML. Now We are ready with Our Model classes so Now it’s time to Add ActionResult in Home Controller. So I have added Action Result which return View with RSS IEnumerable like following.

public ActionResult RssReader()
{
    return View(CodeSimplified.Models.RssReader.GetRssFeed());
}

Now everything is ready. So its time to create a view. So I have created strongly typed view for RSS Model class like following.

@model IEnumerable<CodeSimplified.Models.Rss>
@{
ViewBag.Title = "RssReader";
}

<h2>RssReader</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
   Title
</th>
<th>
   Description
</th>
<th>
   Link
</th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
   <a href="@item.Link" target="_blank">@Html.Encode(item.Title)</a>
</td>
<td>
  @System.Web.HttpUtility.HtmlDecode(item.Description)
</td>
<td>
   <a href="@item.Link" target="_blank">More</a>
</td>
</tr>
}
</table>

Let's run application via pressing F5 and Following is the output as expected.


RssReader

So that’s it. Isn’t that cool? With the few lines of code we have created a Basic RSS Reader. Hope you like it. Stay tuned for more.. Till then Happy Programming..

Shout itkick it on DotNetKicks.com
Share:
Sunday, January 9, 2011

Distinct operator in Linq

Linq operator provides great flexibility and easy way of coding. Let’s again take one more example of distinct operator. As name suggest it will find the distinct elements from IEnumerable. Let’s take an example of array in console application and then we will again print array to see is it working or not. Below is the code for that. In this application I have integer array which contains duplicate elements and then I will apply distinct operator to this and then I will print again result of distinct operators to actually see whether its working or not.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Experiment
{
class Program
{
static void Main(string[] args)
{
int[] intArray = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
var uniqueIntegers = intArray.Distinct();
foreach (var uInteger in uniqueIntegers)
{
Console.WriteLine(uInteger);
}
Console.ReadKey();

}
}
}
Below is output as expected..
DisntictResult

That’s cool..Stay tuned for more.. Happy programming.
Technorati Tags: ,
Shout it
Share:
Sunday, August 29, 2010

LinqDatasource A Great Control for declarative programming

I have used data source control many times and its great it provides us great features for declarative binding. LinqDataSource Control is a great control and it allows us to bind linq queries without writing any code declaratively. Let’s create a example in that example I am not going to write a single line of code and we are going to create view,Update and Delete functionality.

So first we need a table which will have data. So, I am going to use the same table which I have used in my old posts. Below is the table structure for this example.

Table Structure of Linq Data Source Example

Let’s insert some data for that table structure. I have already inserted it in previous example. Just like below.

Table data for linq to SQL Linq Data source example

Now, To bind a linqdatasource we need a Linq-To-SQL Data context class Let’s create it via Project->Right Click->Add New Item –>Go to data tab->Linq-To-SQL classes Just like following.

Add new Linq-To-SQL Classes

After that I have just dragged user data to my data context just like following.

Dragging Table to Linq-to-SQL classes

After creating Our Linq-To-SQL Classes Let’s just Add the A grid View control to my default.aspx page and apply some default format like this.

Adding a GridView from ToolBox and applying format

Now Let’s add a LinqDataSource from the toolbox like following.

Creating A Linq Data Source from ToolBox

Now select the data source and click configure data source as we can see as below.

Configuring Linq Data Source

After clicking on the Configure Data source a wizard will appear which will allow us to select Linq-to-SQL Context class just like following.

Select Linq-To-SQL Class for Linq Data Source

After clicking on next it will allow us to select the Linq-To-SQL Table. In our case it is a Users table so select user table just like following and select * for all columns.

Selecting Linq-To-SQL Table

Click finish now our Linq Data Source is Ready Now select the grid view and select Linq Data source we just created like below.

Setting up Grid view data source as linq datasource

Now our grid view is ready We just need to select Enable Sorting and Enable Paging to give default sorting and paging functionality to grid view. Now do to aspx file and you will see that grid view control is created. I have set two more properties AutoGenerateDeleteButton and AutoGenerateEditButton property of grid view to true as we need to create update and delete functionality also. Just like below.

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" AllowPaging="True" AllowSorting="True"
AutoGenerateColumns="False" DataSourceID="LinqDataSource1"
AutoGenerateDeleteButton="True" AutoGenerateEditButton="True"
DataKeyNames="UserId" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId"
SortExpression="UserId" ReadOnly="True" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True"
ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True"
ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
Then go to Linq Data source and set EnableDelete and EnableUpdate property to true as we need this functionality. Just like following.

<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="Blog.MyBlogDataContext"
EntityTypeName="" TableName="Users"
EnableDelete="True" EnableUpdate="True">
</asp:LinqDataSource>
That’s it now everything is ready lets run the example and see how its works here is the update example and its working fine as should.

Ouput Of Linq Data Source Control

So It’s very easy to create this kind of functionality. Hope this help you.. Happy Programming..

Shout it
kick it on DotNetKicks.com
Share:
Tuesday, August 24, 2010

Using Let Keyword in Linq

I am using Linq-To-Object in my current project to remove some extra loops and I have found one of the great keyword in Linq called ‘Let’. Let keyword provides facility to declare a temporary variable inside the Linq Query.We can assign the result of manipulation to temporary variable inside query and we can use that temporary variable to another manipulation.

Let’s take a simple example of Linq query I am using an integer array to find square and after finding the square of the integer value I will use let keyword to find square value which are greater then 20. Here is the my query for that.

protected void Page_Load(object sender, EventArgs e)
{

int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8 };
var Result = from i in intArray
let square = i * i
where square>20
select square;
foreach (int i in Result)
{
Response.Write(i.ToString());
Response.Write("\n");
}
}
Here is the result of that query as expected.
LetResult

Let keyword is more useful when you are working with directories and files,xml manipulations so here possibilities are unlimited. Hope this will help you.. Happy Programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Wednesday, August 18, 2010

Entity Framework 4.0- Bind Stored Procedure with Result Entity class

Microsoft Entity Framework version 4.0 is a brand new ORM(Object Relational Mapper) from Microsoft. It’s provides now some new features which are not there in the earlier version of Entity framework. Let’s walk through a simple example of a new features which will create a new Entity class based on stored procedure result. We will use same table for this example for which they have used earlier for Linq Binding with Custom Entity.

Below is the table which have simple fields like first name,last name etc.

SQL Table for Entity Example.

Let’s insert some data like following.

Sample data for Entity Framework Example

Below is the stored procedure which I am going to use for this example which will simply fetch data from the table.

CREATE PROCEDURE dbo.GetAllUsers

AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]

FROM dbo.Users
Now let’s create Entity model class just like below via Project->Add New Item->Go to Data tab and then select ADO.NET Entity Data Model.

Adding a New Enity model class for Entity Framework example

Once you click add a dialog box will appear which will ask for Data Model Contents there are two options Generate From Database and another one is Empty Model. Generate from database will create a Entity model from the ready made database while Empty model enable us to create a model first and then it will allow us to create a database from our model. We are going to use Generate From database for this example. Select Generate From Database like following and click Next.

Generating Model from database for Entity Framework 4.0 Example

After click on the next it will ask for database connection string like following where you need to apply connection string for that. I am already having connection string in my web.config so i just selected like below otherwise you need to create one via clicking on new connection. Also you need to specify the connection string name in web.config so it will put a connection string in connection string section with that name.

MyConnection

Once you click next it will fetch the all database objects information like Tables,Views and Stored Procedure like following. Here our purpose is to work with stored procedure so I just selected the stored procedure and selected the GetAllUsers Stored Procedure.

Selecting Stored procedure

After that it will create a Entity Model class in solution explorer.Now we want to bind the stored procedure with result class so first we need to create function which will call ‘GetAllUser’ stored procedure. To create function we just need to select Our Entity Model class and then go to Model Browser and select the Stored Procedure and right click->Add Function Import like following image.

Importing a function from stored procedure example.

It will start a new wizard and will go to next step like following image which will have four options 1. None 2. Scalars 3. Complex 4. Entities and there will be a button Get Column information once you click it. It will gather all the column information of stored procedure result set and then click ‘Create New Complex Type’ It will create a new complex type from the gathered column information.

Gathering a column info and then

You can also rename that class so I have renamed the class as ‘User Info’ like following.

UserInfo

Now click ok and now it will create function which call the stored procedure and will return Object Result set of Type ‘UserInfo’ which we have just created. Now let’s bind that to a simple grid view to see how its works. So Let’s take a simple grid view like below.

<asp:GridView ID="grdUserList" runat="server">
</asp:GridView> 
Now Let’s bind that grid view like following from the code behind file of asp.net like following.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (BlogEntities myEntity = new BlogEntities())
{
grdUserList.DataSource = myEntity.GetAllUsers();
grdUserList.DataBind();
}
}

}
Just run it with Ctrl + F5 and below it the output in browser.

Output of Entity Framework 4.0 Example

That’s it very easy and simple to bind complex type with stored procedure using ADO.NET Entity Framework 4.0. Hope this will help you.. Happy Programming!!!

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Tuesday, August 3, 2010

Binding A Custom Entity Class to stored procedure using Linq-To-SQL

I have already written several post about Linq its a great ORM that we can use in various way. The purpose of this post to demonstrate How we can bind custom entity to stored procedure result with use of Linq-To-SQL. Let’s go through it and you will realize that how easy it will be to bind a Custom Entity to Stored Procedure result.

Let’s first create a simple table to which will hold the user data. It will contain four field like UserId,UserName,FirstName and LastName like following.

SQLTable

Now let’s insert some data into the table like following. SQLTableData

Now let’s create a stored procedure which will return the table data and a new field called Full Name like following. Here full name is a combination of first name and last name

CREATE PROCEDURE dbo.GetAllUsers

AS
SET NOCOUNT ON
SELECT
UserId,
UserName,
FirstName,
LastName,
FirstName + ' ' + LastName AS [FullName]

FROM dbo.Users
After creating a stored procedure it time to create a Linq-To-SQL Right Click Project->Add New Item and Go To->Data and Add LINQ to SQL Classes called MyBlogDataContext.dbml.After creating datacontext class for Linq just drag above store procedure to Linq-To-SQL classes and it will create a function like following.

StoredProcedureInLinqClass

Now let’s add a New Entity Class called UserInfo into Linq-To-SQL DataContext via Right Click Add New Class Just like following.AddClass

After adding class I have added same property as its having in user table and Hence our UserInfo Class will look like following.

UserInfoClass

Now everything is ready Custom Entity Class called UserInfo and we have Our Function ready which will return Stored Procedure output. Here Linq-To-SQL Provides a property called ReturnType If you select function which we have created via dragging a stored procedure in data context class. We just need to select our UserInfo class there just like following and it will bind the stored procedure with that particular UserInfo class. here only condition should be satisfied that Our Custom Entity class should contain all the field with compatible .NET Data types which will return the data. Below is the property which we are talking about.

SelectProperty

Now let’s add grid view to default.aspx page like following and Let’s bind output of stored procedure to that grid view.
<asp:GridView ID="grdUserList" runat="server">
</asp:GridView> 
After placing the Grid View in page here is the code for biding grid view in default.aspx page_load event.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (MyBlogDataContextDataContext myContext =
new MyBlogDataContextDataContext())
{
List<UserInfo> MyUserList =
myContext.GetAllUsers().ToList<UserInfo>();
grdUserList.DataSource = MyUserList;
grdUserList.DataBind(); 
}
}
}
And here is the output which we get in browser after running our web application.

Ouput

That’s it its very easy.. Hope this will help you…

Shout it
Share:
Wednesday, June 23, 2010

Range Operator in Linq.

Linq is almost providing all the functionalities and i have found one another great operator called range operator which will return a sequence of integer number from start point to number of count. Here is the signature of range operator in Linq.
public static IEnumerable<int> Range(int start, int count)
Here the Start means the starting integer of the sequence and count means the number of sequence you want from starting integer. Let’s take a simple example for that where will print 5 to 9 sequence with the help of range operator. Here is the code for that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        var RangeResult = Enumerable.Range(5, 5);
        Console.WriteLine("Range Result");
        foreach (int num in RangeResult)
        {
            Console.WriteLine(num);
        }
    }

}
}
And here is the output for that as expected.

LinqOperators
Hope this will help you..

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:
Saturday, June 19, 2010

Zip operator in Linq with .NET 4.0

Microsoft .NET framework 4.0 is having many features that make developers life very easy. Its also provides some enhancement to Linq also. I just found a great operator called Zip which merge the sequence of two entities.

Here is the explanation of Zip Operator from MSDN.

“The method merges each element of the first sequence with an element that has the same index in the second sequence. If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them”.

Here is the simple console application for the zip. I have taken three arrays for that one is string array, second one is integer array which is having same length as string array and third one is also integer array but having different length then string array. Here is the sample code for that.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] a = { "a", "b", "c", "d" };
int[] num = { 1, 2, 3, 4 };
int[] numdiff = { 1, 2, 3, };


Console.WriteLine("Zip Exmpale with same length");
var ZipResult = a.Zip(num,(ae, ne)=>ae + ", " + ne.ToString());
foreach (string s in ZipResult)
{
Console.WriteLine(s);
}

Console.WriteLine(@"\n\n\nZip Exmpale with diffrent length");
ZipResult = a.Zip(numdiff,(ae, ne)=>ae + ", " + ne.ToString());
foreach (string s in ZipResult)
{
Console.WriteLine(s);
}

Console.ReadKey();
}

}
}
Here is the output of following code as expected.Linq Zip Operator in .NET 4.0

Hope this will help you.

Technorati Tags: ,,
Shout it
kick it on DotNetKicks.com
Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews