• Some Useful Extension Methods On IList<T> zt 武胜


    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)

    Telerik Ad

    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.

  • 相关阅读:
    假如时光倒流,我会这么学习Java
    一位资深程序员大牛给予Java初学者的学习路线建议
    Java基础部分全套教程.
    假如时光倒流,我会这么学习Java
    Window Location对象
    Window Screen对象
    Window
    easyui datagrid 清除缓存方法
    easyui tree扩展tree方法获取目标节点的一级子节点
    JavaScript 对象
  • 原文地址:https://www.cnblogs.com/zeroone/p/3058721.html
Copyright © 2020-2023  润新知