-->

Sunday, April 27, 2014

How to use LINQ Conversion operators in ASP.NET

How to use LINQ Conversion operators in ASP.NET

Introduction

Conversion operators convert a collection to an array. A Conversion operator changes the type of input objects. The different Conversion operators are ToSequence, ToArray, ToList, ToDictionary, ToLookup, OfType, and Cast.
The ToSequence clause simply returns the source argument by changing it to IEnumerable<T>. The ToArray clause enumerates the source sequence and returns an array containing the elements of the sequence. The ToList clause enumerates the source sequence and returns a List<T> containing the elements of the sequence. The ToDictionary clause lists the source sequence and evaluates the keySelector and elementSelector functions for each element to produce the element key and value of the source sequence. The ToLookup clause implements one-to-many dictionary that maps the key to the sequence of values. The OfType clause allocates and returns an enumerable object that captures the source argument. The Cast clause also allocates and returns an enumerable object that captures the source argument.
The syntax of the ToList clause is:


For C#
public static List<T> ToList<T>( this IEnumerable<T> source);

Lets take an simple example

<form id="form1" runat="server">
    <div>
 
        <asp:ListBox ID="ListBox1" runat="server" Height="143px" Width="143px">
        </asp:ListBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            Text="String type" />
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click"
            Text="Integer Type" />
 
    </div>
    </form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Clear();
        var strtype = list.OfType<string>();
        ListBox1.Items.Add("String type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item);
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        ListBox1.Items.Clear();
        var strtype = list.OfType<int>();
        ListBox1.Items.Add("integer type value");
        foreach (var item in strtype)
        {
            ListBox1.Items.Add(item.ToString ());
        }

    }
Code Generate the following output
How to use LINQ Conversion operators in ASP.NET

How to use LINQ Conversion operators in ASP.NET

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved