Select query in LINQ

Select method is used to select one or more items from collection or list object, here we see some example of linq select statement.

variableName.Select(s => s.Name);

There are various ways we can select some records or single record from a collection object.

Let's learn learn how to use Select in LINQ, Here we have an IList collection object with some sample data, we use in examples below.

IList<Country> objList = new List<Country>();   
         
objList.Add(new Country() { Name="India", Language="English" });
objList.Add(new Country() { Name = "USA", Language = "English" });
objList.Add(new Country() { Name = "UK", Language = "English" });
objList.Add(new Country() { Name = "Australia", Language = "English" });
objList.Add(new Country() { Name = "Canada", Language = "Mandarin" });
objList.Add(new Country() { Name = "New Zeland", Language = "English" });
objList.Add(new Country() { Name = "Dubai", Language = "Arabic" });
objList.Add(new Country() { Name = "Spain", Language = "Spanish" });
objList.Add(new Country() { Name = "Russia", Language = "Russian" });

return objList;

LINQ Select in C#

Example of Select in LINQ
We select one particular field called "Name" from above list Country object list

IList<Country> countryList = GetCountryList();
var countryNames = countryList .Where(c => c.Language=="English")
.Select(s => s.Name);

Understand that above variable "countryNames" contain an array of field values which is a type of string, this how we can extract them.

foreach (var _cn in countryNames)
{
    Console.WriteLine("Country : {0}", _cn);

}
Anonymous Select in LINQ

This is an example of LINQ selecting multiple columns, using where clause in linq query

IList<Country> countryList = GetCountryList();
var cDetails = from c in countryList
where   c.Language!="English"
select new { CountryName = c.Name, Language=c.Language};

Now let's see how to extract values from Anonymous variable "cDetails"

foreach (var _cn in cDetails)             
{
    Console.WriteLine("CountryName {0} : Language {1}", _cn.CountryName, _cn.Language);
}

while retrieving property from above variable, use the name you defined inside the new instance, not the actual property name defined in object, for example in above query country name is c.Name , but we have defined the property as CountryName, so, while retrieving, we are using "CountryName", not "Name".

 
Select in LINQ Query Example: LINQ Select in C# Syntax
LINQ (language integrated query) allow you to write query on database objects like ado.net, entity framework etc, LINQ is type safe, easy to convert database object to list objects and business objects in secure and scalable way.
linq Interview Questions Answers
LINQ C# examples | Join Asp.net MVC Course