title: c# List<KeyValuePair> Get Value by Key Or Index
body: <p>How to get <strong>value</strong> by <strong>key</strong> for keyKeyValuePair</p>
  
  <p>I have a  <code>List&lt;KeyValuePair&lt;string, string&gt;&gt;</code></p>
  
  <pre><code>var dataList = new List&lt;KeyValuePair&lt;string, string&gt;&gt;();
  
  // Adding data to the list
  dataList.Add(new KeyValuePair&lt;String, String&gt;("name", "foo"));
  dataList.Add(new KeyValuePair&lt;String, String&gt;("name", "bar"));
  dataList.Add(new KeyValuePair&lt;String, String&gt;("age", "24"));
  </code></pre>
  
  <p>Creating a loop for that list :</p>
  
  <pre><code>foreach (var item in dataList) {
      string key = item.Key;
      string value = item.Value;
  }
  </code></pre>
  
  <p>What i'm trying to do is to get <code>string name = item["name"].Value</code> in some way like this :</p>
  
  <pre><code>foreach (var item in dataList) {
      // Print the value of the key "name" only
      Console.WriteLine(item["name"].Value);
  
      // Print the value of the key "age" only
      Console.WriteLine(item["age"].Value);
  }
  </code></pre>
  
  <p>Or maybe get the <strong>Value</strong> by <strong>Index</strong> like <code>Console.WriteLine(item[0].Value)</code></p>
  
  <p>How could i achieve this?</p>
  
  <p><strong>Note :</strong> <em>i need to use only one foreach not to use separated foreach for every key.</em></p>
  
  <p><strong>Edit 1</strong> if i used <code>if(item.Key == "name") { // do stuff }</code> i won't be able to use the other keys in that if statment, so i need to work in this logic :</p>
  
  <pre><code>if(item.Key == "name") {
      // Print out another key
      Console.WriteLine(item["age"].Value)
  
      // and that will not work because the if statment forced to be the key "name" only
  }
  </code></pre>
  
  <p><strong>Edit 2</strong> i've tried to use <strong>Dictionary</strong> and adding data to it like :</p>
  
  <pre><code>dataList.Add("name", "john");
  dataList.Add("name", "doe");
  dataList.Add("age", "24");
  </code></pre>
  
  <p>and it says <code>An item with the same key has already been added.</code> and i think because i'm adding multiple items with the same key <code>"name"</code> and i need to do that.</p>
  
  <p><strong>Edit 3</strong> What i'm trying to achieve <code>instead of how i try to do it</code> :</p>
  
  <p>I'm trying to loop through the <strong>List</strong> and making a condition if item with key <strong>path</strong> file exists or not like this :</p>
  
  <pre><code>if(File.Exists(item["path"]) { Console.WriteLine(item["name"]) }
  
  // More Explained
  
  foreach (var item in dataList) {
      if (File.Exists(//the key path here//)) {
          MessageBox.Show("File //The key name here// exists.");
      }else {
          MessageBox.Show("File //The key name here// was not found.");
      }
  }
  </code></pre>
  
  <p>and the issue that i can't use item["path"] that way .. all i can do is item.Key &amp; item.Value</p>