将多个对象作为值添加到字典中的键

时间:2016-03-02 20:10:01

标签: c# dictionary

我的任务是从CSV文件中读取并将文件内容放入字典中。

问题是,每个被读入的行都将具有字典中已存在的键。我被告知要将每行读入的值(从类对象)添加到与该行相关的键中,即该帐户。

因此文件样本在每一行上都是这样的,大约有10个帐户,但是有8,000行:

Account1,value1,value2,value3

Account1,value1,value2,value3

所以我被要求做的是当有一个已经存在的非常密钥时我需要在对象中添加(每行读入)到该值。

但是当我被要求用一个物体做这个时,这真的让我很困惑。我理解字典的方式是,如果键/值对是这样的(string,int):

key1,5

key1,10

当我将第二个值添加到distinct键时,它将如下所示: key1,15

在使用像int这样的简单值时,我没有任何问题可以理解。

但如果我使用一个类作为我的价值:

    public class DataRecord
    {
        public string account;
        public int open;
        public int buy;
        public int sell;
        public double settleMM;
        public string underlying;
        public string symbol;
    }

到目前为止,这是我的应用程序:

    static void Main(string[] args)
    {
        double dParseSettleMM;
        int iParseOpen;
        int iParseBuy;
        int iParseSell;
        string sUnderlyingControl = string.Empty;
        string sUnderlying = string.Empty;
        string sAccount = string.Empty;
        string sAccountControl = string.Empty;

        var path = @"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReaderList\Position_2016_02_25.0415.csv";

        Dictionary<string, DataRecord> vSummaryResults = new Dictionary<string, DataRecord>();

        //Sets up control to switch between sorted lists.
        Console.WriteLine("Enter 1 to sort by Account, 2 to sort by Underlying, 3 to sort by Account and Underlying");
        string control = Console.ReadLine();

        //open reader
        StreamReader r = new StreamReader(path);
        StreamWriter vWriteFile = new StreamWriter("Positions2.csv");

        //Consume first line
        r.ReadLine();

        //While loop to populate List with record Objects
        while (!r.EndOfStream)
        {

            DataRecord records = new DataRecord();
            var line = r.ReadLine();
            var values = line.Split(',');

            //Need to add into dictionary...
            if (vSummaryResults.ContainsKey(records.account))
            {
                vSummaryResults[records.account].open += records.open;
            }
            else
            {
                vSummaryResults.Add(records.account, records);
            }
        }

    }

编辑:这是我的具体问题。我被告知这段代码已经有效,我想要了解的是如何以及为什么并尝试将其可视化以理解它。

当我将它添加到字典中时,该类中的每个字段发生了什么?将我的DataRecord类用作值,是否只有这些字段的多个实例?

1 个答案:

答案 0 :(得分:3)

使您的字典值成为DataRecords的列表(或其他集合)。

Dictionary<string, List<DataRecord>> vSummaryResults = new Dictionary<string, List<DataRecord>>();

然后,您可以将在执行期间找到的任何新值添加到该列表中。

选项1:我继续修改你的代码来做到这一点。

static void Main(string[] args)
{
    double dParseSettleMM;
    int iParseOpen;
    int iParseBuy;
    int iParseSell;
    string sUnderlyingControl = string.Empty;
    string sUnderlying = string.Empty;
    string sAccount = string.Empty;
    string sAccountControl = string.Empty;

    var path = @"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReaderList\Position_2016_02_25.0415.csv";

    Dictionary<string, List<DataRecord>> vSummaryResults = new Dictionary<string, List<DataRecord>>();

    //Sets up control to switch between sorted lists.
    Console.WriteLine("Enter 1 to sort by Account, 2 to sort by Underlying, 3 to sort by Account and Underlying");
    string control = Console.ReadLine();

    //open reader
    StreamReader r = new StreamReader(path);
    StreamWriter vWriteFile = new StreamWriter("Positions2.csv");

    //Consume first line
    r.ReadLine();

    //While loop to populate List with record Objects
    while (!r.EndOfStream)
    {

        DataRecord records = new DataRecord();
        var line = r.ReadLine();
        var values = line.Split(',');

        //Need to add into dictionary...
        if (vSummaryResults.ContainsKey(records.account))
        {
            vSummaryResults[records.account].Add(record);
        }
        else
        {
            vSummaryResults.Add(records.account, new List<DataRecord>());
            vSummaryResults[records.account].Add(record);
        }
    }

}

选项2:由于您无法使用选项1.这将序列化每个记录并将其附加到键的值。然后,您可以通过','将其拆分并反序列化。上面的方法更好,但是如果你不能使用它,那么这应该可行。

static void Main(string[] args)
{
    double dParseSettleMM;
    int iParseOpen;
    int iParseBuy;
    int iParseSell;
    string sUnderlyingControl = string.Empty;
    string sUnderlying = string.Empty;
    string sAccount = string.Empty;
    string sAccountControl = string.Empty;

    var path = @"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReaderList\Position_2016_02_25.0415.csv";

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

    //Sets up control to switch between sorted lists.
    Console.WriteLine("Enter 1 to sort by Account, 2 to sort by Underlying, 3 to sort by Account and Underlying");
    string control = Console.ReadLine();

    //open reader
    StreamReader r = new StreamReader(path);
    StreamWriter vWriteFile = new StreamWriter("Positions2.csv");

    //Consume first line
    r.ReadLine();

    //While loop to populate List with record Objects
    var serializer = new JavaScriptSerializer();
    while (!r.EndOfStream)
    {

        DataRecord records = new DataRecord();
        var line = r.ReadLine();
        var values = line.Split(',');

        //Need to add into dictionary...
        if (vSummaryResults.ContainsKey(records.account))
        {
            vSummaryResults[records.account] += "," + serializer.Serialize(record);
        }
        else
        {
            vSummaryResults.Add(records.account, serializer.Serialize(record));
        }
    }

}