static DataTable dtable = new DataTable();
static DataColumn dc = new DataColumn();
static DataRow Dr;
static void Main()
{
CreateTable();
for (int i = 0; i < 3; i++)
{
Dr = dtable.NewRow();
Dr["MId"] = i;
Dr["CId"] = i + 1;
Dr["FId"] = i + 2;
Dr["PId"] = i;
dtable.Rows.Add(Dr);
}
var query = from t in dtable.AsEnumerable()
group t by new
{
Mid = t.Field<Int32>("MId"),
PId = t.Field<Int32>("PId")
} into g
select new
{
MId = g.Key.Mid,
PId = g.Key.PId
};
foreach (var v in query)
{
Console.WriteLine("{0} {1}", v.MId, v.PId);
}
}
public static void CreateTable()
{
//MId CId FId PId
dc = new DataColumn("MId", Type.GetType("System.Int32"));
dtable.Columns.Add(dc);
dc = new DataColumn("CId", Type.GetType("System.Int32"));
dtable.Columns.Add(dc);
dc = new DataColumn("FId", Type.GetType("System.Int32"));
dtable.Columns.Add(dc);
dc = new DataColumn("PId", Type.GetType("System.Int32"));
dtable.Columns.Add(dc);
}
2.按PID分组 获取倒数第二条信息
static DataTable table = new DataTable();
static DataColumn dc = new DataColumn();
static void Main()
{
Createtable();
table.Rows.Add(1, 2,"2010-1-1");
table.Rows.Add(2, 3, "2010-1-1");
table.Rows.Add(3, 4, "2010-1-1");
table.Rows.Add(4, 5, "2010-1-1");
table.Rows.Add(5, 2, "2010-1-2");
table.Rows.Add(6, 3, "2010-1-2");
table.Rows.Add(7, 4, "2010-1-2");
table.Rows.Add(8, 5, "2010-1-2");
var query = from dt in table.AsEnumerable()
where new int[] { 2, 3, 4 }.Contains(dt.Field<Int32>("PID"))
orderby dt.Field<DateTime>("CreateDate") descending
group dt by dt.Field<Int32>("PID") into g
let n = (from d in g.Take(2).Skip(1) select d).FirstOrDefault()
select new
{
ID = n.Field<Int32>("ID"),
PID = g.Key,
CreateDate = n.Field<DateTime>("CreateDate")
};
query.ToList().ForEach(m => Console.WriteLine("{0}\t{1}\t{2}\t",m.ID,m.PID,m.CreateDate));
}
public static void Createtable()
{
dc = new DataColumn("ID", Type.GetType("System.Int32"));
table.Columns.Add(dc);
dc = new DataColumn("PID", Type.GetType("System.Int32"));
table.Columns.Add(dc);
dc = new DataColumn("CreateDate", Type.GetType("System.DateTime"));
table.Columns.Add(dc);
}