Sabtu, 26 Oktober 2013

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

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
{
   tempVar.Field1,
   tempVar.Field2
};

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
{
s.Name,
s.Age
};
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

Tidak ada komentar:

Posting Komentar