C# select new Example: LINQ

Use select new to project into data structures. Loop over the result with foreach.

Select new. A query expression can create a new data structure. This structure is composed of compound objects. With the select new clause, we create new objects of an anonymous type as the result of a query.ObjectLINQ

Note: These keywords are contextual. The "new" keyword has other uses in the C# language.


Example. The select new clause creates an anonymous type instance. In this program, we set the Value property of the anonymous type to the element itself. Then we set the Id property to the result of the Id method.

Finally: You can loop over the AnonymousType instances in the query expression result. We use var to simplify the syntax.


Tip: This query expression transformed the string array into a collection of objects with a Value and Id property.

C# program that uses select new clause 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++; } } Output { Value = one, Id = 0 } { Value = two, Id = 1 } { Value = three, Id = 2 } { Value = four, Id = 3 } { Value = , Id = -1 } { Value = seven, Id = 4 }

HTML. This example constructs HTML strings from a string array. In each anonymous type instance, an Html property and a Length property are present. We display them to the screen. This is not the fastest way to write this code.

Tip: For ideal performance when combining many strings together, consider a StringBuilder or a char array.

StringBuilderChar Array
C# program that projects strings 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); } } } Output <p>cat</p> 3 <p>dog</p> 3 <p>mouse</p> 5

Summary. With select new, we project elements into anonymous types. We demonstrated this clause. This syntax allows us to construct anonymous data structures. These are created as they are evaluated (lazily).

And: You can avoid declaring classes to store this data entirely if you wish to.

However: Classes clarify and improve programs, like a form of built-in documentation, and anonymous types lack these positive features.

Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to