Skip to main content
 首页 » 编程设计

c#之如何在 ASP.NET/C# 中将数据表转换为字典

2024年02月13日11birdshome

下面的DataTable:

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,ClassName”组成,值由“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>"); 
} 

有没有更快的方法?

假设key是'1,A',Value应该是'1000,student666'和'1200,student222'

请您参考如下方法:

那就开始吧。使用 Linq,您可以将它们分组,然后根据需要执行字符串连接。

// 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); 
}