如何转换数据表中ASP.NET/C#到词典 [英] How to convert datatable to dictionary in ASP.NET/C#
本文介绍了如何转换数据表中ASP.NET/C#到词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
的数据表
如下:
ClassID ClassName StudentID StudentName
1 A 1000 student666
2 B 1100 student111
5 C 1500 student777
1 A 1200 student222
2 B 1080 student999
字典键由的ClassID,类名和值是由StudentID,StudentName的。
The dictionary key is composed of "ClassID ,ClassName " and value is composed of "StudentID,StudentName" .
Dictionary<string, string> d = new Dictionary<string, string>();
foreach (DataRow dr in table.Rows)
{
string key=dr["ClassID"].ToString() + dr["ClassName"].ToString();
if (!d.ContainsKey(key))
{
//Do something();......
}
else
{
//Do something();......
}
}
foreach (var s in d.Keys)
{
Response.Write(s+"|+"+d[s]+"<br>");
}
有一个更快的方法?
Is there a faster way?
假定键'1,A',值应该是'1000,student666'和'1200,student222
assume that key is '1,A' ,Value should be ' 1000,student666' and '1200,student222'
推荐答案
下面去即可。使用LINQ,你可以将它们分组,然后,如果你想进行字符串连接。
Here goes then. Using Linq, you can group them then perform string concatenation if you want.
// Start by grouping
var groups = table.AsEnumerable()
.Select(r => new {
ClassID = r.Field<int>("ClassID"),
ClassName = r.Field<string>("ClassName"),
StudentID = r.Field<int>("StudentID"),
StudentName = r.Field<string>("StudentName")
}).GroupBy(e => new { e.ClassID, e.ClassName });
// Then create the strings. The groups will be an IGrouping<TGroup, T> of anonymous objects but
// intellisense will help you with that.
foreach(var line in groups.Select(g => String.Format("{0},{1}|+{2}<br/>",
g.Key.ClassID,
g.Key.ClassName,
String.Join(" and ", g.Select(e => String.Format("{0},{1}", e.StudentID, e.StudentName))))))
{
Response.Write(line);
}
这篇关于如何转换数据表中ASP.NET/C#到词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文