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

それではどうぞ。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 に答える
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);
                }

            }

Reference Dictionary.Add メソッド

OR ELSE Onkelborgの回答を試す

辞書に複合キーを使用するには?

于 2013-07-02T02:21:56.577 に答える
0

ここで注意が必要なのは、複合キー (ClassID、ClassName) です。それを特定したら、このサイトで解決策を簡単に検索できます。

ここで指摘されているように、タプルを使用することをお勧めします:複合キー ディクショナリ

于 2013-07-02T01:39:10.510 に答える
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.WriteくださいConsole.Write。テスト用の DataTable も生成しています。アプリケーションに既に存在するものを使用できるはずです。Class/Student クラスに関する限り、ここにはいくつかのオプションがあります。ここで示したように、2 つの別個のクラスを作成することも、同じクラスを使用することも、Tupleクラスを使用することもできます。読みやすさと保守性が向上するため、2 つの別個のクラスを使用することをお勧めします。

それらを出力する必要がある場合は、辞書などは必要ないことに注意してください。

// 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 の文字列値をキーとして使用することです。たとえば、最初の行のキーには文字列値 "1|A" を使用し、2 行目のキーには文字列値 "2|B" を使用します。

于 2013-07-02T01:43:29.703 に答える