简体   繁体   中英

Add Multiple values to a specific Key In a Dictionary in C#

I have 6 Dictionaries where I am saving key1,value1 and Key1,Value2 depending on the conditions of plate, bowl or spoon.

Firstly I was saving different values in different Dictionaries, but now I want to save the values related to plates like : PlateID, color and value of the condition (100) for the key as name="plate1".

similarly for the bowl and spoon, I want to eliminate the last 3 dictionaries and use only the first 3 dictionaries to save these values.

New Implementation of Class:

abstract class Silver
{
    public double SilverId { get; set; }
    public double InnerTextValue { get; set; }
    public double Color { get; set; }
}

class PlateValues : Silver{ }
class BowlValues : Silver { }
class SpoonValues : Silver{ }

Dictionaries:

    private static IDictionary<string, Silver> plateValues = new Dictionary<string, Silver>();
    private static IDictionary<string, Silver> bowlValues = new Dictionary<string, Silver>();
    private static IDictionary<string, Silver> spoonValues = new Dictionary<string, Silver>();

I am adding values depending on the conditions as below: C# Code

        XmlDocument itemDoc = new XmlDocument();
        itemDoc.Load(@"C:/XML/sample.xml");
        Console.WriteLine("sample has {0} children.",
        itemDoc.DocumentElement.ChildNodes.Count);

        // iterate through top-level elements
        foreach (XmlNode CrockeryNode in itemDoc.DocumentElement.ChildNodes)
        {
            foreach(XmlNode silver in  CrockeryNode.ChildNodes)
            {
                foreach (XmlNode silvertypeNode in CrockeryNode .ChildNodes)
                {
                    foreach (XmlNode childNodeAttributes in silvertypeNode )
                    {
                        XmlElement ruleElement = (XmlElement)silvertypeNode ;
                        //adding to list
                        manifestStatus.Add(ruleElement.Attributes["silverid"].Value);

                        foreach (XmlNode childNodeAttrib in childNodeAttributes.ChildNodes)
                        {
                            foreach (XmlNode childNodeConditions in childNodeAttrib.ChildNodes)
                            {
                                foreach (XmlNode childNodeCond in childNodeConditions.ChildNodes)

                                    if (childNodeCond.Name.ToUpper() == "CONDITION")
                                    {
                                        string[] temp = (childNodeAttrib.Attributes["name"].Value).Split(new Char[] { '.' });
                                        if (temp[0].Equals("plate"))
                                        {
                                            plateValues.Add(childNodeAttrib.Attributes["name"].Value,
                                            new PlateValues
                                            {
                                                 SilverId = Convert.ToDouble(ruleElement.Attributes["SilverId "].Value),
                                                 InnerTextValue = Convert.ToDouble(childNodeCond.InnerText),
                                                 Color= Convert.ToDouble(childNodeCond.Attributes["color"].Value)
                                            });

                                        }
                                        else if (temp[0].Equals("bowl"))
                                        {
                                            bowlValues.Add(childNodeAttrib.Attributes["name"].Value,
                                            new BowlValues
                                            {
                                                 SilverId = Convert.ToDouble(ruleElement.Attributes["SilverId "].Value),
                                                 InnerTextValue = Convert.ToDouble(childNodeCond.InnerText),
                                                 Color= Convert.ToDouble(childNodeCond.Attributes["color"].Value)
                                            });
                                        }
                                        else
                                        {
                                            spoonValues.Add(childNodeAttrib.Attributes["name"].Value,
                                            new SpoonValues
                                            {
                                                 SilverId = Convert.ToDouble(ruleElement.Attributes["SilverId "].Value),
                                                 InnerTextValue = Convert.ToDouble(childNodeCond.InnerText),
                                                 Color= Convert.ToDouble(childNodeCond.Attributes["color"].Value)
                                            });
                                        }
                                         break;
                                    }
                            }
                        }
                    }
                }

Samle XML File:

<?xml version="1.0" encoding="utf-8"?>
<crockery version="2" lastmodified="2015-08-06 03:53:06.207">
  <silver>
    <silvertype silverid="8504p" >
        <attributes>
            <attribute name="plate1" type="int">
                <conditions>
                    <condition type="shine" color="White">100</condition>   
                </conditions>
            </attribute>
            <attribute name="plate4" type="int">
                <conditions>
                    <condition type="shine" color="gold">87</condition> 
                </conditions>
            </attribute>

        </attributes>
    </silvertype>

    <silvertype silverid="3487s" >
        <attributes>
            <attribute name="spoon2" type="int">
                <conditions>
                    <condition type="shine" color="black">58</condition>    
                </conditions>
            </attribute>
            <attribute name="spoon6" type="int">
                <conditions>
                    <condition type="shine" color="gold">45</condition> 
                </conditions>
            </attribute>

        </attributes>
    </silvertype>

    <silvertype silverid="2398b" >
        <attributes>
            <attribute name="bowl7" type="int">
                <conditions>
                    <condition type="shine" color="black">8</condition> 
                </conditions>
            </attribute>
            <attribute name="bowl4" type="int">
                <conditions>
                    <condition type="shine" color="gold">45</condition> 
                </conditions>
            </attribute>    
        </attributes>
    </silvertype>
  </silver>
</crockery>

While Executing I get exception. 在此处输入图片说明

I get the aboveexception at plateValues.Add(childNodeAt

if (temp[0].Equals("plate"))
{
                                            plateValues.Add(childNodeAttrib.Attributes["name"].Value,
                                            new PlateValues
                                            {
                                                 SilverId = Convert.ToDouble(ruleElement.Attributes["SilverId "].Value),
                                                 InnerTextValue = Convert.ToDouble(childNodeCond.InnerText),
                                                 Color= Convert.ToDouble(childNodeCond.Attributes["color"].Value)
                                            });
}

Am I proceeding wrong?

You could use a structure as value

struct myStruct
{
    int value1, value2;
    string value3;
}

Dictionary<string,myStruct> myDictionary = new Dictionary<string,myStruct>();

myDictionary.Add("Key", new myStruct() {value1=12, ...});

There are a few ways to do this, but I would set up a OOP hierarchy. This allows you to later add spoon-specific properties or methods:

abstract class Silver
{
    public double Id {get; set;}
    public double Value {get; set;}
}

class Plate : Silver {}
class Spoon : Silver {}
class Bowl : Silver {}

And since it looks like all your names are unique, you would only need one dictionary:

Dictionary<string, Silver> silvers = new Dictionary<string, Silver>();

And you can instantiate the various types as you go along. For example for a plate:

if (temp[0].Equals("plate"))
{
    silvers.Add(childNodeAttrib.Attributes["name"].Value,
        new Plate 
        {
            Id = Convert.ToDouble(ruleElement.Attributes["silverid"].Value),
            Value = Convert.ToDouble(childNodeCond.InnerText)
        });
}

Then if for example, you want to enumerate over only the plates, you can use IEnumerable.OfType<T> :

var myPlates = silvers.OfType<Plate>();

You could of course forgo the above and just use a simple enum to denote the SilverType :

enum SilverType { Plate, Spoon, Bowl }

class Silver
{
    public double Id {get; set;}
    public double Value {get; set;}
    public SilverType SilverType {get; set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM