0

I have a dataTable with 4 columns , I want to select one column without foreach or any other expensive loop and my result must be a new data table with one column ,How can I do this;

DataTable leaveTypesPerPersonnel = LeaveGroup.GetLeaveTypesPerPersonnels(dtPersonnel.row);

leaveTypesPerPersonnel has this columns :

[ID,Guid,LeaveTypeID,Code]

I want Filter leaveTypesPerPersonnel wihtout foreach and get new datatable with just Column [ID]

NOTE: Output must be a Datatable With one column.

1

3 Answers 3

3
 leaveTypesPerPersonnel.Columns.Remove("Guid");
 leaveTypesPerPersonnel.Columns.Remove("LeaveTypeID");
 leaveTypesPerPersonnel.Columns.Remove("Code");

or

 DataTable dt= new DataView(leaveTypesPerPersonnel).ToTable(false,"ID");
Sign up to request clarification or add additional context in comments.

Comments

0

You should be able to run a quick LINQ statement against the data table.

var results = (from item in leaveTypesPerPersonnel
               select item.ID);

This will give you an IEnumerable if I remember correctly. It's not a DataTable, but might provide a solution to your problem as well.

3 Comments

This is a loop. While he said ForEach in the question, I believe he meant any loop.
I believe the intent of the poster is not to have to do a for each loop of his data set to build a new structure, not that methods that utilize a loop internally cannot be utilized.
That is an interesting belief, the poster says "foreach or any other expensive loop". Sound like he or she does not want a loop.
-1

Here is a try on how to search and convert the result to DataTable

 var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().Where(x=> x["ID"] == 21).CopyToDataTable().DefaultView.ToTable(false, "ID");

Or

 var dataTable = leaveTypesPerPersonnel.Select("ID = 21").CopyToDataTable().DefaultView.ToTable(false, "ID");

Or

   var dataTable = leaveTypesPerPersonnel.Rows.Cast<DataRow>().ToList().CopyToDataTable().DefaultView.ToTable(false, "ID");

4 Comments

This is a loop. While he said ForEach in the question, I believe he meant any loop.
Also this is only returning one row. The poster is clearly asking for a table not a row.
my friend CopyToDataTable return a DataTable and ToTable also return a DataTable. its upp to him to specify which rows to return. he can have all rows in the DataTable
hahaha no i just added a third Or where you can have all rows without filter. i did not change anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.