Some Useful Extension Methods On IList zt

來源:互聯網
上載者:User
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 included a  public static void WriteDelimitedFile<T>(this IEnumerable<T> list, string logfile, string delimiter) extension method.

Here is the code for the extension methods:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.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)
        {
             for (int i = 0; i < iColCount; i++)
             {
                 if (!Convert.IsDBNull(dr[i]))
                 {
                      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:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using ListExtensions;

namespace ConsoleApplication1
{

    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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.