1

I have a small problem, which I just cannot find how to fix it.

For my data table, Dictionar.DtDomenii, I need to copy the unique data from my other data table, Dictionar.Dt.

I wrote a query, but when using query.CopyToDataTable() to copy the data into my DtDomenii table, the "CopyToDataTable" function does not show...

Am I doing something wrong? Is there an easier way to copy distinct data (categories from my example) from one data table to another?

PS: I've already read the information from MSDN https://msdn.microsoft.com/en-us/library/bb386921%28v=vs.110%29.aspx

void LoadCategories()
{
    var query = (from cat in Dictionar.dt.AsEnumerable()
                 select new 
                        {
                            categorie = categorii.Field<string>("Categoria")
                        }).Distinct();

    // This statement does not work: 
    Dictionar.dtDomenii = query.CopyToDataTable();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BogdanM
  • 957
  • 4
  • 15
  • 32

1 Answers1

0

Only collections of DataRows can use the CopyToDataTable method. For example:

DataTable table = new DataTable();
table.AsEnumerable().CopyToDataTable(); // this works

List<DataRow> dataRows = new List<DataRow>();
dataRows.CopyToDataTable(); // this also works

List<string> strings = new List<string>();
strings.CopyToDataTable(); // this does not work

The select new... part of your query is converting the DataRows into objects. You need to convert the objects back into DataRows before you can use the CopyToDataTable method.

You might have better luck doing something like this:

DataTable copy = Dictionar.dt
   .AsEnumerable()       // now an enumerable of DataRow
   .Distinct()           // remove duplicates, still an enumerable of DataRow
   .CopyToDataTable();   // done!

You can also make a complete copy of the table with Dictionar.dt.Copy(), then remove the duplicate rows manually.

Chris
  • 3,328
  • 1
  • 32
  • 40