C#對(duì)DataTable中的某列進(jìn)行分組
有時(shí)候我們從數(shù)據(jù)庫(kù)中查詢出來(lái)數(shù)據(jù)之后,需要按照DataTable的某列進(jìn)行分組,可以使用下面的方法實(shí)現(xiàn),代碼如下:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTableGroupDemo
{
class Program
{
static void Main(string[] args)
{
// 準(zhǔn)備數(shù)據(jù)
DataTable dt = new DataTable();
// 創(chuàng)建列
DataColumn dcName = new DataColumn("Name", typeof(string));
DataColumn dcAge = new DataColumn("Age", typeof(Int32));
DataColumn dcScore = new DataColumn("Score", typeof(Int32));
// 添加列
dt.Columns.Add(dcName);
dt.Columns.Add(dcAge);
dt.Columns.Add(dcScore);
// 添加數(shù)據(jù)
dt.Rows.Add(new object[] { "Tom", 23, 67 });
dt.Rows.Add(new object[] { "Tom", 23, 67 });
dt.Rows.Add(new object[] { "Jack", 21, 100 });
dt.Rows.Add(new object[] { "Greey", 24, 56 });
dt.Rows.Add(new object[] { "Kevin", 24, 77 });
dt.Rows.Add(new object[] { "Tom", 23, 82 });
dt.Rows.Add(new object[] { "Greey", 24, 80 });
dt.Rows.Add(new object[] { "Jack", 21, 90 });
#region 使用Linq expression to DataTable group by
var query = from p in dt.AsEnumerable()
group p by new { name = p.Field<string>("Name"),score=p.Field<Int32>("Score") } into m
select new
{
Name = m.Key.name,
Score=m.Key.score
};
#endregion
// 輸出
Console.WriteLine("Linq");
foreach (var item in query)
{
Console.WriteLine(item);
}
Console.WriteLine("GroupBy");
IEnumerable<IGrouping<string, DataRow>> result = dt.Rows.Cast<DataRow>().GroupBy<DataRow, string>(dr => dr["Name"].ToString());
foreach (IGrouping<string, DataRow> ig in result)
{
Console.WriteLine("key=" + ig.Key + ":");
foreach (DataRow dr in ig)
{
Console.WriteLine(dr["Name"].ToString().PadRight(10) + dr["Age"].ToString().PadRight(10) + dr["Score"].ToString().PadRight(10));
}
}
Console.ReadKey();
}
}
}程序運(yùn)行效果

到此這篇關(guān)于C#對(duì)DataTable某列進(jìn)行分組的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)用戶自定義控件中嵌入自己的圖標(biāo)
這篇文章主要介紹了C#實(shí)現(xiàn)用戶自定義控件中嵌入自己的圖標(biāo),較為詳細(xì)的分析了C#實(shí)現(xiàn)自定義控件中嵌入圖標(biāo)的具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-03-03
Unity3D 計(jì)時(shí)器的實(shí)現(xiàn)代碼(三種寫(xiě)法總結(jié))
這篇文章主要介紹了Unity3D 計(jì)時(shí)器的實(shí)現(xiàn)代碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-04-04
C# 系統(tǒng)熱鍵注冊(cè)實(shí)現(xiàn)代碼
簡(jiǎn)單點(diǎn)說(shuō)就是為程序制定快捷鍵勒。。很多軟件都帶熱鍵功能的,通過(guò)以下方式可以實(shí)現(xiàn)2個(gè)鍵或3個(gè)鍵的快捷鍵,相當(dāng)之使用,具體實(shí)現(xiàn)方法看后文吧。2009-02-02
C#中List轉(zhuǎn)IList的實(shí)現(xiàn)
本文主要介紹了C#中List轉(zhuǎn)IList的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
重寫(xiě)、隱藏基類(new, override)的方法
重寫(xiě)、隱藏基類(new, override)的方法,需要的朋友可以參考一下2013-03-03
關(guān)于C# TabPage如何隱藏的問(wèn)題
TabPage沒(méi)有Visible屬性,所以只能通過(guò)設(shè)置將其與父控件(tabcontrol)的關(guān)聯(lián)性去除就好了,如下面代碼:2013-04-04

