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
Example
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.
Code
private IList _list = new List();
public InitializeList()
{
// Set data
_list.Add(1);
_list.Add(2);
_list.Add(3);
_list.Add(4);
_list.Add(5);
_list.Add(6);
}
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));
}
}
Input1
2
3
4
5
6
Output"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.
