Last active
February 7, 2023 22:29
-
-
Save PhilMurwin/367466a108fdddc00d94b36d6fa690ce to your computer and use it in GitHub Desktop.
Extension methods to serialize lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.IO; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using System.Xml; | |
using System.Xml.Serialization; | |
namespace Extensions | |
{ | |
public static class ListExtensions | |
{ | |
// https://stackoverflow.com/a/14696980/368318 | |
public static List<T> NoEmptyList<T>(this List<T> data) where T : new() | |
{ | |
if (data.Count() == 0) | |
{ | |
data = new List<T> { new T { } }; | |
} | |
return data; | |
} | |
public static XmlDocument ToXML<T>( this List<T> list, string rootElement = "root" ) | |
{ | |
XmlDocument xmlDoc = new XmlDocument(); | |
using ( var memoryStream = new MemoryStream() ) | |
using ( var writer = new XmlTextWriter( memoryStream, Encoding.Unicode ) ) | |
{ | |
XmlSerializer ser = new XmlSerializer( typeof( List<T> ), new XmlRootAttribute( rootElement ) ); | |
ser.Serialize( writer, list ); | |
memoryStream.Position = 0; //rewind the stream before reading back | |
xmlDoc.Load( memoryStream ); | |
} | |
return xmlDoc; | |
} | |
public static DataTable ToDataTable<T>( this List<T> list ) | |
{ | |
DataTable dataTable = new DataTable( typeof( T ).Name ); | |
//Get all the properties | |
PropertyInfo[] Props = typeof( T ).GetProperties( BindingFlags.Public | BindingFlags.Instance ); | |
foreach ( PropertyInfo prop in Props ) | |
{ | |
//Setting column names as Property names | |
dataTable.Columns.Add( prop.Name ); | |
} | |
foreach ( T item in list ) | |
{ | |
var values = new object[Props.Length]; | |
for ( int i = 0; i < Props.Length; i++ ) | |
{ | |
//inserting property values to datatable rows | |
values[i] = Props[i].GetValue( item, null ); | |
} | |
dataTable.Rows.Add( values ); | |
} | |
//put a breakpoint here and check datatable | |
return dataTable; | |
} | |
public static void ToFile<T>(this IList<T> data, string path) | |
{ | |
var dir = Path.GetDirectoryName(path); | |
Directory.CreateDirectory(dir); | |
var json = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented); | |
File.WriteAllText(path, json); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment