SORU
10 AĞUSTOS 2009, PAZARTESİ


IEnumerable DataTable dönüştürmek

Güzel bir şekilde bir DataTable için bir IEnumerable dönüştürmek için var mı?

Yansıma özellikleri ve değerleri almak için kullanabilirsiniz, ama bu biraz verimsiz gibi görünüyor, orada bir şey yap-mı?

(Örnekler gibi biliyorum: ObtainDataTableFromİEnumerable)

EDİT:
question Bu bir sorun, bir null değerleri işleme yolladı beni.
Aşağıda yazdığım kod düzgün null değerleri işleme.

public static DataTable ToDataTable<T>(this IEnumerable<T> items) {  
    // Create the result table, and gather all properties of a T        
    DataTable table = new DataTable(typeof(T).Name); 
    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  

    // Add the properties as columns to the datatable
    foreach (var prop in props) { 
        Type propType = prop.PropertyType; 

        // Is it a nullable type? Get the underlying type 
        if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
            propType = new NullableConverter(propType).UnderlyingType;  

        table.Columns.Add(prop.Name, propType); 
    }  

    // Add the property values per T as rows to the datatable
    foreach (var item in items) {  
        var values = new object[props.Length];  
        for (var i = 0; i < props.Length; i  ) 
            values[i] = props[i].GetValue(item, null);   

        table.Rows.Add(values);  
    } 

    return table; 
} 

CEVAP
10 AĞUSTOS 2009, PAZARTESİ


Şuna bir bakın: Convert List/IEnumerable to DataTable/DataView

Benim kod uzantısı bir yönteme değiştirdim:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i  )
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • bcbauer

    bcbauer

    7 ŞUBAT 2007
  • beautyexchange

    beautyexchan

    4 EYLÜL 2006
  • MyCyberAcademy

    MyCyberAcade

    2 EKİM 2011