C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: These keywords are contextual. The "new" keyword has other uses in the C# language.
NewFinally: You can loop over the AnonymousType instances in the query expression result. We use var to simplify the syntax.
VarTip: This query expression transformed the string array into a collection of objects with a Value and Id property.
ArrayPropertyC# 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 }
Tip: For ideal performance when combining many strings together, consider a StringBuilder or a char array.
StringBuilderChar ArrayC# 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
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.
Class