Some useful extension methods on ilist ZT

Source: Internet
Author: User
Tags visual studio 2010
Some useful extension methods on ilist <t> By Peter Bromberg
Instantly DTSearch terabytes of popular data types; hundreds of reviews, etc .!
Often I need to convert a list of a certain type to a CSV string, or to a datatable. Here I provide four extension methods:

1) public static datatable todatatable <t> (this ilist <t> data) (List <t> to datatable.
2) public static string tocsv <t> (this ilist <t> data) (List <t> to CSV string.
3) Public static string tocsv (this datatable DT) (datatable to CSV string.
4) Public static void writedelimitedfile <t> (this ienumerable <t> list, string logfile, string delimiter)

Extension methods are great for utility purposes as there is no need to reference
The class in which they are defined, nor to instantiate any objects.

If you have a datatable "DT" you can simply call DT. tocsv () to get a CSV
Delimited string. Likewise if you have a list <person> "people"
You can call people. tocsv (). I have also encodedPublic Static VoidWritedelimitedfile <t> (ThisIenumerable <t> list, string logfile, string delimiter) Extension Method.

Here is the code for the extension methods:

UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. componentmodel;
UsingSystem. Data;
UsingSystem. IO;
UsingSystem. LINQ;
UsingSystem. text;

Namespace Listextensions
{
Public Static Class Listextensions
{
Public Static Datatable todatatable <t> ( This Ilist <t> data)
{
Propertydescriptorcollection props =
Typedescriptor. getproperties (typeof (t ));
Datatable table = New Datatable ();
For (INT I = 0; I <props. Count ; I ++)
{
Propertydescriptor prop = props [I];
Table. columns.Add (Prop. Name, Prop. propertytype );
}
Object [] values = New Object [props. Count ];
Foreach (T item In Data)
{
For (INT I = 0; I <values. length; I ++)
{
Values [I] = props [I]. getvalue (item );
}
Table. rows. Add (Values );
}
Return Table;
}

Public Static String tocsv <t> ( This Ilist <t> data)
{
Propertydescriptorcollection props = typedescriptor. getproperties (typeof (t ));
Stringbuilder sb = New Stringbuilder ();

For (INT I = 0; I <props. Count ; I ++)
{
Propertydescriptor prop = props [I];
SB. append (prop. Name );
If (I <props. Count -1)
{
SB. append ( "," );
}
}
SB. append (environment. newline );
VaR values = New Object [props. Count ];
Foreach (T item In Data)
{
For (INT I = 0; I <values. length; I ++)
{
Values [I] = props [I]. getvalue (item );
SB. append (Values [I]. tostring ());
If (I <values. Length-1)
{
SB. append ( "," );
}
}
SB. append (environment. newline );
}
Return SB. tostring ();
}

Public Static String tocsv ( This Datatable DT)
{
Memorystream MS = New Memorystream ();
Streamwriter Sw = New Streamwriter (MS );
Int icolcount = DT. columns. Count ;
For (INT I = 0; I <icolcount; I ++)
{
SW. Write (Dt. Columns [I]);
If (I <icolcount-1)
{
SW. Write ( "," );
}
}
SW. Write (SW. newline );

foreach (datarow Dr in DT. rows)
{< br> for (INT I = 0; I {< br> If (! convert . isdbnull (Dr [I])
{< br> SW. write (Dr [I]. tostring ();
}

If (I <icolcount-1)
{
SW. Write ( "," );
}
}
SW.Write (SW. newline );
}
SW. Close ();
Return System. Text. encoding. utf8.getstring (Ms. toarray ());
}
Public Static Void Writedelimitedfile <t> ( This Ienumerable <t> list, string logfile, string delimiter)
{
Using (VAR Sw = file. appendtext (logfile ))
{
VaR props = typeof (T). getproperties ();
VaR headernames = props. Select (x => X. Name );
SW. Writeline (String. Join (delimiter, headernames. toarray ()));
Foreach (VAR item In List)
{
VaR Item1 = item;
VaR values = props
. Select (x => X. getvalue (Item1, Null )?? "" )
. Select (x => X. tostring ())
. Select (x => X. Contains (delimiter) | X. Contains ( "\ N" )? "\"" + X + "\"" : X );
SW. Writeline (String. Join (delimiter, values. toarray ()));
}
SW. Close ();
}
}
}
}

And here is a short console application to exercise the above:

UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. componentmodel;
UsingSystem. Data;
UsingSystem. LINQ;
UsingSystem. text;
UsingListextensions;

NamespaceLeleapplication1
{

Public Class Test
{
Public String name {Get; set ;}
Public String address {Get; set ;}
Public String city {Get; set ;}
Public String state {Get; set ;}
Public String zipcode {Get; set ;}
}
Class Program
{
Static Void Main (string [] ARGs)
{
List < Test > Tests =New List < Test > ();

For (INT I = 0; I <3; I ++)
{
Test T = New Test ()
{
Name = "Peter Bromberg" ,
Address = "123 high st #10" + I,
City = "Pocahontas" ,
State = "FL" ,
Zipcode = "32323"
};
Tests. Add (T );
}
Datatable dt = tests. todatatable ();
String csv2 = DT. tocsv ();
String CSV = tests. tocsv ();

Console . Writeline (CSV );
Console . Writeline ( "============================================== ==============================" );
Console . Writeline (Csv2 );
Tests. writedelimitedfile ( @ "C: \ temp \ log.csv" , "," );
Console . Writeline ( " Any Key to quit ." );
Console . Readkey ();
}
}
}

You can download the Visual Studio 2010 solution here.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.