<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged datatable</title>
<link>https://coderlegion.com/tag/datatable</link>
<description>Powered by Question2Answer</description>
<item>
<title>Filling a DataSet or a DataTable from a LINQ Query Result Set</title>
<link>https://coderlegion.com/20001/filling-a-dataset-or-a-datatable-from-a-linq-query-result-set</link>
<description>&lt;p&gt;Modern .NET development often relies on LINQ (Language Integrated Query) to retrieve, filter, and transform data efficiently. LINQ provides a clean and readable way to work with collections, databases, XML files, and many other data sources. However, there are situations where applications still require traditional ADO.NET objects such as DataSet and DataTable for reporting, legacy integrations, or data binding purposes.&lt;/p&gt;
&lt;p&gt;Understanding how to fill a DataSet or DataTable from a LINQ query result set is an important skill when working with both modern and legacy .NET applications.&lt;/p&gt;
&lt;p&gt;Why Convert LINQ Results to DataTable or DataSet?&lt;/p&gt;
&lt;p&gt;LINQ queries typically return collections such as IEnumerable, IQueryable, or List. While these structures are excellent for application logic, some components require DataTable or DataSet objects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Common scenarios include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Reporting tools that accept DataTable as a data source.&lt;br&gt;
Legacy applications built around ADO.NET.&lt;br&gt;
Exporting data to Excel or CSV.&lt;br&gt;
Binding data to older UI controls.&lt;br&gt;
Data exchange between different application layers.&lt;/p&gt;
&lt;p&gt;Converting LINQ results into DataTable structures bridges the gap between modern querying techniques and traditional data handling mechanisms.&lt;/p&gt;
&lt;p&gt;Understanding LINQ Query Results&lt;/p&gt;
&lt;p&gt;Consider a simple list of employees:&lt;/p&gt;
&lt;p&gt;var employees = new List&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;new Employee { Id = 1, Name = &quot;John&quot;, Department = &quot;IT&quot; },
new Employee { Id = 2, Name = &quot;Sarah&quot;, Department = &quot;HR&quot; },
new Employee { Id = 3, Name = &quot;David&quot;, Department = &quot;IT&quot; }
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;};&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;A LINQ query might look like:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;var result = from emp in employees&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;         where emp.Department == &quot;IT&quot;
         select emp;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This query returns a collection of Employee objects. To use this data in older systems, we may need to populate a DataTable.&lt;/p&gt;
&lt;p&gt;Creating a DataTable from LINQ Results&lt;/p&gt;
&lt;p&gt;The first step is creating the structure of the DataTable.&lt;/p&gt;
&lt;p&gt;DataTable dt = new DataTable();&lt;/p&gt;
&lt;p&gt;dt.Columns.Add(&quot;Id&quot;, typeof(int));&lt;br&gt;
dt.Columns.Add(&quot;Name&quot;, typeof(string));&lt;br&gt;
dt.Columns.Add(&quot;Department&quot;, typeof(string));&lt;/p&gt;
&lt;p&gt;After defining the columns, populate rows from the LINQ result.&lt;/p&gt;
&lt;p&gt;foreach (var employee in result)&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;dt.Rows.Add(
    employee.Id,
    employee.Name,
    employee.Department
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;This approach gives complete control over the schema and data population process.&lt;/p&gt;
&lt;p&gt;Using CopyToDataTable()&lt;/p&gt;
&lt;p&gt;When LINQ operates directly on DataTable rows, .NET provides a built-in extension method called CopyToDataTable().&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;
&lt;p&gt;DataTable employeesTable = GetEmployeesTable();&lt;/p&gt;
&lt;p&gt;var filteredRows =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from row in employeesTable.AsEnumerable()
where row.Field&amp;lt;string&amp;gt;(&quot;Department&quot;) == &quot;IT&quot;
select row;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;DataTable resultTable = filteredRows.CopyToDataTable();&lt;/p&gt;
&lt;p&gt;This method automatically creates a new DataTable and copies matching rows.&lt;/p&gt;
&lt;p&gt;Benefits include:&lt;/p&gt;
&lt;p&gt;Less code.&lt;br&gt;
Faster implementation.&lt;br&gt;
Preserves schema automatically.&lt;/p&gt;
&lt;p&gt;CopyToDataTable() is often the easiest solution when querying existing DataTable objects.&lt;/p&gt;
&lt;p&gt;Filling a DataSet with LINQ Results&lt;/p&gt;
&lt;p&gt;A DataSet can contain multiple DataTables.&lt;/p&gt;
&lt;p&gt;Create a DataSet:&lt;/p&gt;
&lt;p&gt;DataSet ds = new DataSet();&lt;/p&gt;
&lt;p&gt;Add the DataTable:&lt;/p&gt;
&lt;p&gt;ds.Tables.Add(dt);&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;You can also add multiple tables:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;DataTable employeeTable = GetEmployeeData();&lt;br&gt;
DataTable departmentTable = GetDepartmentData();&lt;/p&gt;
&lt;p&gt;DataSet companyDataSet = new DataSet();&lt;/p&gt;
&lt;p&gt;companyDataSet.Tables.Add(employeeTable);&lt;br&gt;
companyDataSet.Tables.Add(departmentTable);&lt;/p&gt;
&lt;p&gt;DataSets are useful when managing related tables and complex reporting structures.&lt;/p&gt;
&lt;p&gt;Generic Method for Converting LINQ Results to DataTable&lt;/p&gt;
&lt;p&gt;A reusable generic solution can save development time.&lt;/p&gt;
&lt;p&gt;public static DataTable ToDataTable(IEnumerable data)&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DataTable table = new DataTable(typeof(T).Name);

PropertyInfo[] properties =
    typeof(T).GetProperties();

foreach (PropertyInfo property in properties)
{
    table.Columns.Add(
        property.Name,
        Nullable.GetUnderlyingType(property.PropertyType)
        ?? property.PropertyType);
}

foreach (T item in data)
{
    DataRow row = table.NewRow();

    foreach (PropertyInfo property in properties)
    {
        row[property.Name] =
            property.GetValue(item) ?? DBNull.Value;
    }

    table.Rows.Add(row);
}

return table;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;Usage:&lt;/p&gt;
&lt;p&gt;var employeesDataTable = ToDataTable(result);&lt;/p&gt;
&lt;p&gt;This generic approach works with virtually any LINQ result collection.&lt;/p&gt;
&lt;p&gt;Performance Considerations&lt;/p&gt;
&lt;p&gt;When dealing with large datasets, performance becomes important.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Best practices include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Filter data at the database level whenever possible.&lt;br&gt;
Avoid unnecessary DataTable conversions.&lt;br&gt;
Use projections to select only required columns.&lt;br&gt;
Minimize reflection usage in high-performance scenarios.&lt;br&gt;
Cache metadata when repeatedly converting objects.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Example projection:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;var result =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;employees.Select(e =&amp;gt; new
{
    e.Id,
    e.Name
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This reduces memory consumption and processing overhead.&lt;/p&gt;
&lt;p&gt;Common Challenges&lt;/p&gt;
&lt;p&gt;Developers often encounter issues such as:&lt;/p&gt;
&lt;p&gt;Empty Query Results&lt;br&gt;
if(result.Any())&lt;br&gt;
{&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;DataTable table = result.CopyToDataTable();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;}&lt;/p&gt;
&lt;p&gt;Calling CopyToDataTable() on an empty collection can throw an exception.&lt;/p&gt;
&lt;p&gt;Null Values&lt;/p&gt;
&lt;p&gt;Always handle null values properly:&lt;/p&gt;
&lt;p&gt;row[&quot;Name&quot;] =&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;employee.Name ?? DBNull.Value;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Data Type Mismatches&lt;/p&gt;
&lt;p&gt;Ensure DataTable column types match source object properties to prevent runtime errors.&lt;/p&gt;
&lt;p&gt;Careful validation helps maintain data integrity and application stability.&lt;/p&gt;
&lt;p&gt;Real-World Applications&lt;/p&gt;
&lt;p&gt;Many enterprise applications still rely heavily on DataTables and DataSets.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Typical use cases include:&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Financial reporting systems.&lt;br&gt;
Inventory management platforms.&lt;br&gt;
Business intelligence dashboards.&lt;br&gt;
Legacy Windows Forms applications.&lt;br&gt;
Data export utilities.&lt;br&gt;
Integration with third-party reporting engines.&lt;/p&gt;
&lt;p&gt;LINQ provides modern querying capabilities, while DataTable and DataSet maintain compatibility with established enterprise workflows.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Filling a DataSet or DataTable from a LINQ query result set allows developers to combine the readability and flexibility of LINQ with the compatibility and structure of ADO.NET. Whether using manual row population, CopyToDataTable(), or generic conversion methods, understanding these techniques can significantly improve data processing workflows.&lt;/p&gt;
&lt;p&gt;As organizations continue modernizing their applications, developers frequently encounter environments where both LINQ and traditional ADO.NET coexist. Mastering the conversion between these technologies ensures smoother integrations, cleaner code, and more maintainable enterprise applications.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Sumita&lt;br&gt;
Web Developer&lt;/strong&gt;&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/20001/filling-a-dataset-or-a-datatable-from-a-linq-query-result-set</guid>
<pubDate>Tue, 09 Jun 2026 04:50:51 +0000</pubDate>
</item>
<item>
<title>ReactJS DataTable</title>
<link>https://coderlegion.com/2805/reactjs-datatable</link>
<description>&lt;p&gt;In web applications—especially reporting or monitoring applications—we often need to display a large amount of data from an API. To make data loading faster, we typically design our APIs to support &lt;em&gt;pagination&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;In classic _JavaScript &lt;em&gt;frameworks like &lt;/em&gt;&lt;strong&gt;jQuery&lt;/strong&gt;_, we are familiar with using &lt;strong&gt;DataTables&lt;/strong&gt; to display paginated data tables. But how do we use &lt;strong&gt;DataTables&lt;/strong&gt; in &lt;em&gt;ReactJS&lt;/em&gt;?&lt;/p&gt;
&lt;p&gt;First, we create react application by executing in our terminal/CMD&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm create-react-app react-demo-datatable
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then in our terminal/CMD we have to install datatable package.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install react-data-table-component
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Don't forget to install &lt;strong&gt;lodash.debounce&lt;/strong&gt; package for our search data table. &lt;strong&gt;lodash.debounce&lt;/strong&gt; is a utility function from the Lodash library that delays a function’s execution until after a specified amount of time has passed since it was last called. i will prevent Too many API calls (e.g. every user type) to Maximalize performance issue.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;npm install lodash.debounce
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Then let's adjust our &lt;em&gt;App.js&lt;/em&gt; to look like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;import React, { useState, useEffect } from &quot;react&quot;;
import DataTable from &quot;react-data-table-component&quot;;
import debounce from &quot;lodash.debounce&quot;;

// Dummy local dataset
const localData = [
  {
    NO_RESI: &quot;PLMAA16157522113&quot;,
    RECEIVER_NAME: &quot;John Doe&quot;,
    RECEIVER_DIVISION: &quot;IT&quot;,
    CREATED_DATE: &quot;2025-04-11&quot;,
    STATUS_NAME: &quot;Complete&quot;,
    STATUS: &quot;002&quot;,
  },
  {
    NO_RESI: &quot;PLMAA16157522112&quot;,
    RECEIVER_NAME: &quot;Jane Doe&quot;,
    RECEIVER_DIVISION: &quot;Finance&quot;,
    CREATED_DATE: &quot;2025-04-10&quot;,
    STATUS_NAME: &quot;On Progress&quot;,
    STATUS: &quot;001&quot;,
  },
  // Add more dummy items here
];

const statusOptions = [
  { key: &quot;001&quot;, status: &quot;On Progress&quot; },
  { key: &quot;002&quot;, status: &quot;Complete&quot; },
];

const columns = [
  { name: &quot;No Resi&quot;, selector: (row) =&amp;gt; row.NO_RESI, sortable: true },
  { name: &quot;Receiver&quot;, selector: (row) =&amp;gt; row.RECEIVER_NAME, sortable: true },
  { name: &quot;Receiver Division&quot;, selector: (row) =&amp;gt; row.RECEIVER_DIVISION, sortable: true },
  { name: &quot;Created Date&quot;, selector: (row) =&amp;gt; row.CREATED_DATE, sortable: true },
  { name: &quot;Status&quot;, selector: (row) =&amp;gt; row.STATUS_NAME, sortable: true },
  {
    name: &quot;Action&quot;,
    cell: (row) =&amp;gt; (
      &amp;lt;button className=&quot;bg-blue-500 text-black px-3 py-1 rounded hover:bg-blue-600&quot;&amp;gt;
        Detail
      &amp;lt;/button&amp;gt;
    ),
  },
];

const customStyles = {
  headCells: {
    style: {
      backgroundColor: &quot;#919492&quot;,
      color: &quot;#333&quot;,
      fontWeight: &quot;bold&quot;,
      fontSize: &quot;14px&quot;,
    },
  },
};

export default function App() {
  const [data, setData] = useState([]);
  const [search, setSearch] = useState(&quot;&quot;);
  const [statusFilter, setStatusFilter] = useState(&quot;&quot;);
  const [loading, setLoading] = useState(false);

  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);

  const filterLocalData = (page, size, searchText, statusKey) =&amp;gt; {
    setLoading(true);

    let filtered = [...localData];

    if (searchText) {
      filtered = filtered.filter(
        (item) =&amp;gt;
          item.NO_RESI.toLowerCase().includes(searchText.toLowerCase()) ||
          item.RECEIVER_NAME.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    if (statusKey) {
      filtered = filtered.filter((item) =&amp;gt; item.STATUS === statusKey);
    }

    const start = (page - 1) * size;
    const paginated = filtered.slice(start, start + size);

    setData(paginated);
    setTotalRows(filtered.length);
    setLoading(false);
  };

  useEffect(() =&amp;gt; {
    filterLocalData(currentPage, perPage, search, statusFilter);
  }, [search, statusFilter, perPage, currentPage]);

  const handlePageChange = (page) =&amp;gt; {
    setCurrentPage(page);
  };

  const handlePerRowsChange = (newPerPage, page) =&amp;gt; {
    setPerPage(newPerPage);
    setCurrentPage(page);
  };

  const debouncedSearch = debounce((val) =&amp;gt; {
    setSearch(val);
  }, 500);

  return (
    &amp;lt;div className=&quot;w-full p-4&quot;&amp;gt;
      &amp;lt;div className=&quot;flex justify-between items-center mb-4 gap-4&quot;&amp;gt;
        &amp;lt;select
          className=&quot;p-2 border rounded&quot;
          value={statusFilter}
          onChange={(e) =&amp;gt; setStatusFilter(e.target.value)}
        &amp;gt;
          &amp;lt;option value=&quot;&quot;&amp;gt;All Status&amp;lt;/option&amp;gt;
          {statusOptions.map((opt) =&amp;gt; (
            &amp;lt;option key={opt.key} value={opt.key}&amp;gt;
              {opt.status}
            &amp;lt;/option&amp;gt;
          ))}
        &amp;lt;/select&amp;gt;

        &amp;lt;input
          type=&quot;text&quot;
          placeholder=&quot;Search...&quot;
          className=&quot;p-2 border rounded w-full max-w-md&quot;
          onChange={(e) =&amp;gt; debouncedSearch(e.target.value)}
        /&amp;gt;
      &amp;lt;/div&amp;gt;

      &amp;lt;DataTable
        columns={columns}
        data={data}
        progressPending={loading}
        pagination
        paginationServer
        paginationTotalRows={totalRows}
        onChangePage={handlePageChange}
        onChangeRowsPerPage={handlePerRowsChange}
        customStyles={customStyles}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Our react project will look like this:&lt;/p&gt;
&lt;p&gt;&lt;img src=&quot;https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fegooutlr1096x7gqjl1.png&quot; alt=&quot;Demo App&quot;&gt;&lt;/p&gt;
</description>
<category>Components</category>
<guid isPermaLink="true">https://coderlegion.com/2805/reactjs-datatable</guid>
<pubDate>Fri, 25 Apr 2025 03:46:07 +0000</pubDate>
</item>
</channel>
</rss>