Generic class to CSV (all properties)

前端 未结 5 1279
梦如初夏
梦如初夏 2021-02-13 02:42

Im looking for a way to create CSV from all class instances.

What i want is that i could export ANY class (all of its instances) to CSV.

Can some1 direct me to p

5条回答
  •  太阳男子
    2021-02-13 03:22

    My answer is based on Michael Kropat's answer from above.

    I added two functions to his answer because it didn't want to write straight to file as I still had some further processing to do. Instead I wanted the header information separate to the values so I could put everything back together later.

        public static string ToCsvString(T obj)
        {
            var fields =
                from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
                let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
                select mi;
    
            return QuoteRecord(FormatObject(fields, obj));
        }
    
        public static string GetCsvHeader(T obj)
        {
            var fields =
                from mi in typeof(T).GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
                where new[] { MemberTypes.Field, MemberTypes.Property }.Contains(mi.MemberType)
                let orderAttr = (ColumnOrderAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnOrderAttribute))
                select mi;
    
            return QuoteRecord(fields.Select(f => f.Name));
        }
    

提交回复
热议问题