2009-09-10 6 views
2

J'ai une méthode dans mon application qui renseigne DataTable avec les données en utilisant le code suivant:Populate DataTable avec LINQ en C#

DataTable dt = this.attachmentsDataSet.Tables["Attachments"]; 

foreach (Outlook.Attachment attachment in this.mailItem.Attachments) 
{ 
    DataRow dr = dt.NewRow(); 
    dr["Index"] = attachment.Index; 
    dr["DisplayName"] = String.Format(
     CultureInfo.InvariantCulture, 
     "{0} ({1})", 
     attachment.FileName, 
     FormatSize(attachment.Size)); 
    dr["Name"] = attachment.FileName; 
    dr["Size"] = attachment.Size; 

    dt.Rows.Add(dr); 
} 

Je me demandais si je pouvais obtenir les mêmes fonctionnalités LINQ pour raccourcir ce code un peu. Des idées?

+0

À quoi utilisez-vous le datatable? Est-ce pour les insertions db? – spender

+0

Je n'utilise pas de base de données. C'est pour remplir une source de données listbox. – RaYell

Répondre

1

Eh bien ce code isnt plus ou moins Linq, mais je ne une méthode externsion qui prend un IList et le transforme en DataTable pour vous.

public static DataTable ToDataTable<T>(this IList<T> theList) 
    { 
     DataTable theTable = CreateTable<T>(); 
     Type theEntityType = typeof(T); 

     // Use reflection to get the properties of the generic type (T) 
     PropertyDescriptorCollection theProperties = TypeDescriptor.GetProperties(theEntityType); 

     // Loop through each generic item in the list 
     foreach (T theItem in theList) 
     { 
      DataRow theRow = theTable.NewRow(); 

      // Loop through all the properties 
      foreach (PropertyDescriptor theProperty in theProperties) 
      { 
       // Retrieve the value and check to see if it is null 
       object thePropertyValue = theProperty.GetValue(theItem); 
       if (null == thePropertyValue) 
       { 
        // The value is null, so we need special treatment, because a DataTable does not like null, but is okay with DBNull.Value 
        theRow[theProperty.Name] = DBNull.Value; 
       } 
       else 
       { 
        // No problem, just slap the value in 
        theRow[theProperty.Name] = theProperty.GetValue(theItem); 
       } 
      } 

      theTable.Rows.Add(theRow); 
     } 

     return theTable; 
    } 
0

Vous devez d'abord déterminer si vous pouvez interroger this.mailItem.Attachments et s'il est possible, vous pouvez convertir résultat de la requête à un datatable de méthode d'extension créer par Steve Sloka ...

1

Oui, facile

public void FillFromList(List<T> col) 
    { 
     Type elementType = typeof(T); 

     // Nested query of generic element list of property 
     // values (using a join to the DataTable columns) 
     var rows = from row in col 
        select new 
        { 
         Fields = from column in m_dataTable.Columns.Cast<DataColumn>() 
           join prop in elementType.GetProperties() 
            on column.Caption equals prop.Name 
           select prop.GetValue(row, null) 
        }; 

     // Add each row to the DataTable 
     int recordCount = 0; 
     foreach (var entry in rows) 
     { 
      m_dataTable.Rows.Add(entry.Fields.ToArray()); 
     } 

Cela suppose que les propriétés sur T sont les mêmes que les colonnes DataTable.