سؤال

I want to take fist n number of records from a data table.

I don't want to run a loop which I already know.

I'm trying to do this

DataTable dt = dtResult.AsEnumerable().Take(n)

is the right way..?

what is the process to make this "n records" to be in another datatable..?

هل كانت مفيدة؟

المحلول

Yes, this is a correct way to take first N rows from your data table. Use CopyToDataTable extension to create new data table from query result:

DataTable dt = dtResult.AsEnumerable()
                       .Take(n)
                       .CopyToDataTable();

نصائح أخرى

lazyberezovsky's answer is correct, however perhaps you'd like to use AsQueryable rather than AsEnumerable if you would like to do some more fancy things than just Take as the IQueryable interface gives you more freedom to write expressions against collections that you haven't got in memory yet. I'd say IQueryable is more suitable for interaction with a database than IEnumerable is. More info: What is the difference between IQueryable and IEnumerable?

DataTable dt = dtResult.AsQueryable()
                       .Take(n)
                       .CopyToDataTable();

Try this .CopyToDataTable(). E.g.

DataTable dt = dtResult.AsEnumerable().Take(5).CopyToDataTable();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top