.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Articles >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Lambda Expressions Extension Method 8 - Select() with Anonymous Type Creation

Posted By:Jean Paul       Posted Date: May 11, 2011    Points: 200    Category: LINQ    URL: http://www.dotnetspark.com  

Lambda Expressions Extension Method 8 - Select() with Anonymous Type Creation

Select() with Anonymous Type Creation

As a continuation of Select() method, we can have anonymous type creation as well.  The anonymous type are those without a name in our c# source code and the compiler will generate an automatic name for it.

It is convenient that we are free from creating a class and properties.  The following example shows

  • How to specify an anonymous class  in the Select Method
  • How to create the properties of anonymous class
  • How to retrieve the properties of anonymous class

Parameters: Input type and Transformation Method

Return Value: List of Items


In the following example we are using a list of integers and converting them to a class having 2 properties:

  • Value which is the actual value of integer
  • Index  which is the index of the element

The statement _list.Select((i, ix) => new { Value = i, Index = ix }) will do the job.

After converting we are storing the result in a var type.

For retrieving the properties back we use the same var keyword and iterate through a foreach.  The var type allows us to read the properties Value and Index with automatic type inference by IDE.


private IList _list = new List();

  public InitializeList()
  // Set data

  private void SelectAnonymousButton_Click(object sender, EventArgs e)
  var result = _list.Select((i, ix) => new { Value = i, Index = ix });

  foreach (var v in result)  {
  string messsage = "Value={0} at Index={1}";
  MessageBox.Show(string.Format(messsage, v.Value, v.Index));



"Value=1 at Index=0"
"Value=2 at Index=1"
"Value=3 at Index=2"
"Value=4 at Index=3"
"Value=5 at Index=4"
"Value=6 at Index=5"

Extension Method Snapshot

You can find the snapshot of the Select() method usage as provided by Visual Studio.

 Subscribe to Articles


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend