How to Get Selected Fields from List Using LINQ: C#

October 26, 2013 , , 0 Comments

When we bind a list with a control like datagridview, comboBox or listbox, then it will bind all the fields related to list. I have created a list of student with multiple fields i.e. Name, age, city and DOB. Now in this article I will bind only name and age of this list to a Datagridview.

To get selected fields, syntax of LINQ query will be:
var variable = from tempVar in list
select new

Now in our case of Student class the records should be selected through the following C# line of code:
var selectedFields = from s in stuList
select new
dataGridView1.DataSource = selectedFields.ToList();

In the last line of code, it will bind the list to gridview and show only name and age of the students like in following image:

Get selected fields in LINQ: C# windows forms
If all the LINQ methods are not showing in your program then sure about the namespace in your code file i.e. System. Linq;

See Also: How to Bind DataGridView with DataSet

Subhash Sharma

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard. Google