Problem:
Possible Solutions to problem:
- With normal for loop
- With lamda expression and linq
1. With normal for loop:
Following is code from where we can get 3 rows of data table.private DataTable GetFirst3RowViaFor(DataTable dataTable) { DataTable newDataTable = dataTable.Clone(); for(int i=0;i<3;i++) { DataRow row = dataTable.Rows[i]; newDataTable.Rows.Add(row); } return newDataTable; }
Here in this way I have cloned data table structure and then I added first 3 rows of data table to new data table.
2. With lamda expression:
private static DataTable GetFirstThreeRowViaLinq(DataTable dataTable) { return dataTable.Rows.Cast<System.Data.DataRow>().Take(3).CopyToDataTable(); }
That’s it. Hope you liked it. Stay tuned more updates..
linq is best for this :)
ReplyDeleteYes I agree with Aryan
ReplyDeletedst.Tables[0].Rows.OfType().Take(3).CopyToDataTable(). will also do the trick
ReplyDeleteOfType - return only the elements of type x.
Cast - will try to cast all the elements into type x. if some of them are not from this type you will getInvalidCastException
return dataTable.Rows.OfType().Take(3).CopyToDataTable(); will also do the trick.
ReplyDeleteOfType - return only the elements of type x.
Cast - will try to cast all the elements into type x. if some of them are not from this type you will getInvalidCastException
@disqus_dm6TrEz5D2:disqus - Thanks for mentioning
ReplyDelete@Aryan- I agree with you.
ReplyDeletePreviously i use to code using clone in the application, now its better to go for Linq. Ravi has mentioned a good point
ReplyDelete