Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand
  • Advertisements

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

Posted by Paul on November 13, 2011

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<int> _list = new List<int>();

  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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s