8,497
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace Test
{
public class People
{
public string Name{get ;set;}
public string City { get; set; }
public string Sex { get; set; }
}
public static class Extension
{
public static DataTable CopyToDataTable<T>(this IEnumerable<T> array)
{
var ret = new DataTable();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
// if (!dp.IsReadOnly)
ret.Columns.Add(dp.Name, dp.PropertyType);
foreach (T item in array)
{
var Row = ret.NewRow();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
// if (!dp.IsReadOnly)
Row[dp.Name] = dp.GetValue(item);
ret.Rows.Add(Row);
}
return ret;
}
}
public class Linq2DataTable
{
private static List<People> GetData()
{
List<People> list = new List<People>();
list.Add(new People {Name="Bruce",City ="SZ",Sex ="Man"});
list.Add(new People { Name = "John", City = "GZ", Sex = "Man" });
list.Add(new People { Name = "Judy", City = "CS", Sex = "Woman" });
return list;
}
public static void Test()
{
List<People> data= GetData();
var result = from p in data where p.Sex == "Man" select new { Name = p.Name, City = p.City };
DataTable dt = Extension.CopyToDataTable(result);
Console.WriteLine(ToString(dt));
}
public static string ToString(System.Data.DataTable data)
{
StringBuilder sb = new StringBuilder();
int colCount = data.Columns.Count;
foreach (System.Data.DataRow dr in data.Rows)
{
for (int i = 0; i < colCount; i++)
{
string s = (dr[i] == null ? string.Empty : dr[i].ToString());
sb.Append(s);
sb.Append(",");
}
sb.AppendLine();
}
return sb.ToString();
}
}
}