yamon
yamon

Reputation: 45

get first element from list in dictionary c#

I use the following structure

Dictionary<string, List<object>>

I want to get the first element from list for entered certain key.

thank you

Upvotes: 1

Views: 6731

Answers (4)

Kurru
Kurru

Reputation: 14321

Dictionary<string, List<object>> item = new Dictionary<string, List<object>>();
string key="this is the key";
object firstItem = item[key][0];

This code presumes the key exists and that theres at least 1 item in the collection

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

var myValue = myDict[myKey][0];

This doesn't work for you?

Upvotes: 0

Lee
Lee

Reputation: 144126

object item = dictionary[key].First();

or you could use FirstOrDefault if you can't be certain the list contains any items.

Or if you can't be certain the key exists:

object item = dictionary.ContainsKey(key) ? dictionary[key].FirstOrDefault() : null;
if(item != null) { ... }

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190907

if (myDictionary.ContainsKey("myKey"))
   var myItem = myDictionary["myKey"].FirstOrDefault();

Upvotes: 3

Related Questions