1

以下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>");
}

有更快的方法吗?

假设键是 '1,A' ,值应该是 '1000,student666' 和 '1200,student222'

4

5 回答 5

2

尝试这个:

Dictionary<string, string> d = new Dictionary<string, string>();

            foreach (DataRow dr in table.Rows)
            {
                string key=dr["ClassID"].ToString() + "-" + dr["ClassName"].ToString();
                string value=dr["StudentID"].ToString() + "-" + dr["StudentName"].ToString();
                if (!d.ContainsKey(key))
                {
                    d.Add(key, value);
                }

            }

参考 Dictionary.Add 方法

或其他尝试Onkelborg的答案

如何在字典中使用复合键?

于 2013-07-02T02:21:56.577 回答
2

那就去吧。使用 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);
}
于 2013-07-02T02:48:25.230 回答
0

这里有一些东西可以给你一个想法:

using System;
using System.Data;
using System.Collections.Generic;

namespace SO17416111
{
    class Class
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    // Note that definition of Class and Student only differ by name
    // I'm assuming that Student can/will be expanded latter. 
    // Otherwise it's possible to use a single class definition
    class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main()
        {
            DataTable table = GetData();
            Dictionary<Class, List<Student>> d = new Dictionary<Class, List<Student>>();

            foreach (DataRow dr in table.Rows)
            {                
                // If it's possible to get null data from the DB the appropriate null checks
                // should also be performed here
                // Also depending on actual data types in your DB the code should be adjusted as appropriate
                Class key = new Class {Id = (int) dr["ClassID"], Name = (string) dr["ClassName"]};
                Student value = new Student { Id = (int)dr["StudentID"], Name = (string)dr["StudentName"] };

                if (!d.ContainsKey(key))
                {
                    d.Add(key, new List<Student>());
                }
                d[key].Add(value);
            }
            foreach (var s in d.Keys)
            {
                foreach (var l in d[s])
                {
                    Console.Write(s.Id + "-" + s.Name + "-" + l.Id + "-" + l.Name + "\n");
                }
            }
        }

        // You don't need this just use your datatable whereever you obtain it from
        private static DataTable GetData()
        {
            DataTable table = new DataTable();
            table.Columns.Add("ClassID", typeof (int));
            table.Columns.Add("ClassName", typeof (string));
            table.Columns.Add("StudentID", typeof (int));
            table.Columns.Add("StudentName", typeof (string));

            table.Rows.Add(1, "A", 1000, "student666");
            table.Rows.Add(2, "B", 1100, "student111");
            table.Rows.Add(5, "C", 1500, "student777");
            table.Rows.Add(1, "A", 1200, "student222");
            table.Rows.Add(2, "B", 1080, "student999");
            return table;
        }
    }
}

请注意,这可以作为控制台应用程序进行编译和测试 - 我Response.WriteConsole.Write. 我还在生成一个测试数据表,您应该能够使用您的应用程序中已经存在的数据表。就班级/学生班级而言,您有几个选择:您可以有两个单独的班级,如我所展示的,您可以使用同一个班级,甚至可以使用元组班级。我建议您使用两个单独的类,因为它提高了可读性和可维护性。

请注意,如果您只需要输出它们,则不需要字典或任何类似的东西:

// Add null checks and type conversions as appropriate
foreach (DataRow dr in table.Rows)
{
    Response.Write(dr["ClassID"] + "-" + dr["ClassName"] + "-" + dr["StudentID"] + "-" + dr["StudentName"] + "<br>");
}
于 2013-07-02T02:39:39.183 回答
0

这里棘手的是复合键(ClassID,ClassName)。一旦您确定了这一点,就很容易在此站点上搜索解决方案。

我建议使用此处指出的元组:复合键字典

于 2013-07-02T01:39:10.510 回答
0

最简单的方法是使用 ClassID|ClassName 的字符串值作为键。例如,使用字符串值“1|A”作为第一行的键,使用字符串值“2|B”作为第二行的键,等等。

于 2013-07-02T01:43:29.703 回答