Domanda

| FieldName | header | code    | 
| a1        | test   |         |
| a1        | test   | 1       |
| a1        | test   | 2       | 
| a1        | test   | 3       | 
| a1        | test   | 4       | 
| a1        | test   | 5       | 
| b2        | prod   | 1       | 
| b2        | prod   | 2       | 
| b2        | prod   | 3       | 

I have the following code to loop thru the table and add the data in a hashtable. Currently my code only adds one a1 and b2. but what I am planing to do is add them all in my hashtable with a different key. For example: ("a11",value), ("a12",value); ("a13",value); and the same for b2..ect.

 public Hashtable GetData(Table table, string headerType)
    {

        var data = table.CreateSet<SpecFlowData>();
        var hashtable = new Hashtable();
        hashtable.Clear();

        foreach (var currentRow in data)
        {
            var key = currentRow.FieldName;
            var value = new Hashtable();

            GetValue(value, currentRow);

            if (hashtable.ContainsKey(key)) //continue;
            {
                var r = new Random();
                key = key + r.Next();
            }
            var format = (string)value["header"];
            if (headerType == format)
            {
                hashtable.Add(key, value);

            }
            break;
        }


        return hashtable;

     }

Update: Here is the getvalue method:

     private static void GetValue(Hashtable value, SpecFlowData currentRow)
      {
        value.Clear();

        value.Add("code", currentRow.Code);
         value.Add("name", currentRow.FieldName);
        value.Add("header", currentRow.HeaderType);
       }

Why is my data not added properly. thanks for your help.

È stato utile?

Soluzione

You are breaking out of the foreach loop at the end of your first iteration, so there can only be one key-value-pair in your Hashtable.

If you remove the break statement, you will get more values. As @JohnGardner mentioned, you should not use a random, because it may produce identical values. Simply use an increasing integer variable.

So after all, this should do:

public Hashtable GetData(Table table, string headerType)
{
  var data = table.CreateSet<SpecFlowData>();
  var hashtable = new Hashtable(); // no need to clear a newly created Hashtable
  int i = 1;

  foreach (var currentRow in data)
  {
    var key = currentRow.FieldName;
    var value = GetValue(currentRow);

    if (hashtable.ContainsKey(key))
    {
        key = key + i++;
    }
    var format = (string)value["header"];
    if (headerType == format)
    {
      hashtable.Add(key, value);
    }
  }
  return hashtable;
}

private static Hashtable GetValue(SpecFlowData currentRow)
{
  var value = new Hashtable();

  value.Add("code", currentRow.Code);
  value.Add("name", currentRow.FieldName);
  value.Add("header", currentRow.HeaderType);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top