Select
newA C# query expression can create a new data structure. With the select new clause, we create new objects of an anonymous type as the result of a query.
The "select new" keywords are contextual—the "new" keyword has other uses in the C# language. We use these keywords in a query expression (System.Linq
is required).
The select new clause creates an anonymous type instance. In this program, we set the Value and Id in each element—each new object will have a Value and Id.
AnonymousType
instances in the query expression result. We use var
to simplify the syntax.string
array into a collection of objects with a Value and Id property.using System; using System.Linq; class Program { static void Main() { string[] array = { "one", "two", "three", "four", "", "seven" }; // Use Select New. var result = from element in array select new { Value = element, Id = Id(element) }; foreach (var anonymous in result) { string value = anonymous.Value; int id = anonymous.Id; Console.WriteLine(anonymous); } } static int _value; static int Id(string element) { // Get Id. return string.IsNullOrEmpty(element) ? -1 : _value++; } }{ Value = one, Id = 0 } { Value = two, Id = 1 } { Value = three, Id = 2 } { Value = four, Id = 3 } { Value = , Id = -1 } { Value = seven, Id = 4 }
This example constructs HTML strings from a string
array. In each anonymous type instance, an Html property and a Length
property are present.
StringBuilder
or a char
array.using System; using System.Linq; class Program { static void Main() { string[] items = { "cat", "dog", "mouse" }; // Project items into HTML strings. var html = from item in items select new { Html = "<p>" + item + "</p>", Length = item.Length }; // Display all projected values. foreach (var value in html) { Console.WriteLine(value.Html); Console.WriteLine(value.Length); } } }<p>cat</p> 3 <p>dog</p> 3 <p>mouse</p> 5
With select new, we project elements into anonymous types. This syntax allows us to construct anonymous data structures. These are created as they are evaluated (lazily).
You can avoid declaring classes to store this data entirely if you wish to. Classes clarify and improve programs, and anonymous types lack these positive features.