What is the usage of select in C#?
In C#, the select keyword is commonly used in LINQ query statements to select elements from a collection that meet specific criteria. The select keyword transforms the query results into a new collection that contains the elements that meet the specified conditions.
For example, here is a simple demonstration showing how to use the select keyword to choose strings from a collection that are longer than 5 characters.
List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David", "Eve" };
var result = from name in names
where name.Length > 5
select name;
foreach (var item in result)
{
Console.WriteLine(item);
}
In the example above, the select keyword is used to choose strings with a length greater than 5, and store the results in the variable “result”. The strings that meet the criteria are then printed using a foreach loop that goes through the “result” variable.
In conclusion, the select keyword in C# is used to select elements from a collection that meet a certain condition and then transform those elements into a new collection.