0

一意のサブジェクト値がそれに一致する必要があるさまざまなコード値を持つ辞書を作成しようとしています。

CODE    SUBJECT

7DIM-062  Recruitment and Selection

7DIM-063    Recruitment and Selection

7DIM-064    Recruitment and Selection

7DIM-065    Recruitment and Selection

7DIM-066    Recruitment and Selection

7DIM-067    Recruitment and Selection

7DIM-068    Recruitment and Selection

したがって、私が望むのは、要件と選択が一意のキーとして一度辞書に追加され、次に対応するすべてのコードがリストに追加されることだけです。これを行うにはどうすればよいですか?

Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>();

これは私の質問です

OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
    string code = (string)dbReader["CODE"];
    string subject = (string)dbReader["SUBJECT"];
    //???? this is the point where I would want to add the values
    dict.Add(subject, new List<string>().Add(code);
4

3 に答える 3

5

最初に、辞書に既にキーがあるかどうかを確認します。そうでない場合は、List初期化で新しいキーを追加します。

if (!dict.ContainsKey(subject))
{
    dict[subject] = new List<string>();    
}

dict[subject].Add(code);
于 2013-02-12T12:22:19.413 に答える
2

Dictionary.TryGetValue辞書にその主題がすでに含まれているかどうかを確認するために使用できます。次に、新しいコードを追加できます。それ以外の場合は、subject+codeを追加します。

Dictionary<string, List<string>> dict = new Dictionary<string,List<string>>();
while (dbReader.Read())
{
    string code = (string)dbReader["CODE"];
    string subject = (string)dbReader["SUBJECT"];

    List<string> codes;
    if (dict.TryGetValue(subject, out codes))
    {
        codes.Add(code);
    }
    else
    {
        codes = new List<string>() { code };
        dict.Add(subject, codes);
    }
}

2回検索するよりも効率的です。

このメソッドは、ContainsKeyメソッドとItemプロパティの機能を組み合わせたものです。キーが見つからない場合、valueパラメーターはタイプTValueの適切なデフォルト値を取得します。たとえば、整数型の場合は0(ゼロ)、ブール型の場合はfalse、参照型の場合はnullです。コードがディクショナリにないキーに頻繁にアクセスしようとする場合は、TryGetValueメソッドを使用してください。このメソッドを使用すると、ItemプロパティによってスローされたKeyNotFoundExceptionをキャッチするよりも効率的です。このメソッドは、O(1)操作にアプローチします。

于 2013-02-12T12:25:13.013 に答える
2

ルックアップ<string, string>を使用できます:

var subjects = new List<KeyValuePair<string, string>>();
while (dbReader.Read())
{
    string code = (string)dbReader["CODE"];
    string subject = (string)dbReader["SUBJECT"];

    subjects.Add(new KeyValuePair<string, string>(subject, code));
}
// ...
var lookup = subjects.ToLookup(x => x.Key, x => x.Value);
var recruitmentAndSelectionCodes = lookup["Recruitment and Selection"].ToList();
// returns
//     7DIM-062 
//     7DIM-063 
//     etc. 
于 2013-02-12T12:32:27.800 に答える