面朝大海,春暖华开

focus on scientific computue, 3dgis, spatial database
专注于科学计算、GIS空间分析

 

ADO.NET 从DataTable中获取某列含有的不同值的几种方式

private int getCount()  
 {  
 DataTable dt //已知的datadable ,有上万条记录  
 DataTable newDt=dt.DefaultView.ToTable(true, "city");  
 int num=newDt.Rows.Count;  
 return num;  
}
DataTable SourceTable = new SourseTable();
SourceTable.Columns.Add("Code",string);
//...向SourseTable中添加数据
DataView view = new DataView(SourceTable);
string[] columns = {"Code"}
DataTable tarTable  = view.ToTable(true,columns);//得到目标
单列:
 
 
MyDataContext db = new MyDataContext();  
var result = (from p in db.t_Personnel  
                  select p.FirstName).Distinct();  
DataTable dt = new DataTable("SingleDistinct");  
dt.Columns.Add("FirstName");  
foreach (var item in result)  
{  
    DataRow dr = dt.NewRow();  
    dr["FirstName"] = item.ToString();  
    dt.Rows.Add(dr);  
}  
dataGridView1.DataSource = dt;  
  
 
 
多列:
 
 
 
using System.Data;  
using System.Collections;  
namespace Test_Distinct  
{  
    public class PersonDataRowComparer : IEqualityComparer<t_Personnel>  
    {  
        public bool Equals(t_Personnel t1, t_Personnel t2)  
        {  
            return (t1.ID == t2.ID && t1.FirstName == t2.FirstName);  
        }  
        public int GetHashCode(t_Personnel t)  
        {  
            return t.ToString().GetHashCode();  
        }  
    }  
}  
  
MyDataContext db = new MyDataContext();  
IEnumerable distinctRows = db.t_Personnel.ToList().Distinct(new PersonDataRowComparer());  
DataTable dt = new DataTable("SingleDistinct");  
dt.Columns.Add("ID");  
dt.Columns.Add("FirstName");  
dt.Columns.Add("LastName");  
foreach (var item in distinctRows)  
{  
    DataRow dr = dt.NewRow();  
    dr["ID"] = item.ID;  
    dr["FirstName"] = item.FirstName;  
    dr["LastName"] = item.LastName;  
    dt.Rows.Add(dr);  
}  
dataGridView1.DataSource = dt;  
  

 

posted on 2013-01-04 12:05  风过 无痕  阅读(2467)  评论(0编辑  收藏  举报

导航

向日葵支付宝收钱码