Search

Sunday, April 27, 2014
0 comments

How to use LINQ Conversion operators in ASP.NET

3:15 AMSunday, April 27, 2014

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

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top