Contents tagged with Linq

  • 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.

    Example:

    Following is a code for that.

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

    namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var customers = new List<Customer>( new[] { new Customer{FirstName = "Jalpesh",LastName = "Vadgama"}, new Customer{FirstName = "Vishal",LastName = "Vadgama"}, new Customer{FirstName = "Tushar",LastName = "Maru"} } );

            var newCustomers = customers.Where(c =&gt; c.LastName == &quot;Vadgama&quot;);
    
            customers.Add(new Customer {FirstName = &quot;Teerth&quot;, LastName = &quot;Vadgama&quot;});
    
            foreach (var c in newCustomers)
            {
                Console.WriteLine(c.FirstName);
            }
        }
    
        public class Customer
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    
    }
    

    }

    More on my personal blog @www.dotnetjalps.com

    Shout it

  • 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 and 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; }
    }

    Now we are going to create Person class which have Name property and A person can have multiple address so address generic list as property like following.

    public class Person
    {
        public string Name { get; set; }
        public List<Address> Addresses { get; set; }
    }

    Read more>>

  • 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

    Now we have already have table to its time to create a Linq-To-SQL dbml file.

    Read More

    Shout it

  • 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.

    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","Jemit","Jay" };

            Console.WriteLine(&quot;Skipwhile Operator&quot;);
            foreach (var name in names.SkipWhile(s =&gt; s.ToLower().StartsWith(&quot;j&quot;)))
            {
                Console.WriteLine(name);
            }
            Console.WriteLine(&quot;-----------------------------------&quot;);
            Console.WriteLine(&quot;Where Operator&quot;);
            foreach (var name in names.Where(s =&gt; !s.ToLower().StartsWith(&quot;j&quot;)))
            {
                Console.WriteLine(name);
            }
        }
    }
    

    }

    As you can see that in the above code I have a string array called names where I have people’s name as string. Here you can see there are multiple names start with letter “J” in array. Now once we use SkipWhile operator it will skip the elements untill condition is false for first time So it will skip the elements until condition satisfied for the first once you have different condition it will not going skip element even if they are satisfying the condition. While in where it will filter whole collection and print output.

    Let’s run above example. Following is a output as expected.

    image

    That’s it. Hope you like it. Stay tuned for more. Till than happy programming.

    Shout it

  • 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); 
                }
            }
        }
    }

    In the above code I have created a array of string called names and I want to skip names starts with letter “j” with help of ‘SkipWhile’. I am printing each item via for each loop. Following is the output as expected.

    image

    That’s it.Hope you liked it. Stay tuned for more..Till then happy programming.

    Shout it

  • 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.

    http://en.wikipedia.org/wiki/RSS

    http://www.whatisrss.com/.

    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 it

  • 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

  • GUID Vs Int data type as primary key

    Recently one of my friend ask me when I should go for GUID and When I should go for Int as primary key in table. So decided to write a blog post for it. Here are advantages and disadvantage of the GUID and INT. 

    INT Data Type:

    Advantages:

    1. Its required small space in terms of the storage it will only allocates 4 bytes to store data.
    2. Insert and update performance will be faster then the GUID. It will increase the performance of the application.
    3. Easy to index and Join will give best performance with the integer.
    4. Easy to understand and remember
    5. Support of function that will give last value generated like Scope_Indentity()

    Disadvantages:

    1. If you are going to merge table frequently then there may be a chance to duplicated primary key.
    2. Limited range of uniqueness if you are going to store lots of data then it may be chance to run out of storage for INT data type.
    3. Hard to work with distributed tables.

    GUID Data Type:

    Advantages:

    1. It is unique for the current domains. For primary key is uniquely identifies the table.
    2. Less chances of for duplication.
    3. Suitable for inserting and updating large amount of data.
    4. Easy for merging data across servers.

    Disadvantages:

    1. Bigger storage size (16bytes) will occupy more disk size then integer.
    2. Hard to remember and lower performance with Join then integer.
    3. Don’t have function to get last uniquely generated primary key.
    4. A GUID primary Key will added to all the other indexes on tables. So it will decrease the performance.

    Conclusion:

    From above the advantages and disadvantages we can conclude that if you are having very large amount of data in table then go for the GUID as primary key in database. Otherwise INT will give best performance. Hope this will help you. Please post your comment as your opinion.

     

     

    Shout it

  • 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 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

  • 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