Get value from C# lookup

lelol picture lelol · Dec 13, 2011 · Viewed 18.8k times · Source

I'm interested in how to get value from C# lookup structure.

Example:

var myLookup = (Lookup<string, int>)data.Rows.Cast<DataRow>().ToLookup(row => row["Name"], row => row["Id"]);

foreach (var myLookupItem in myLookup)
                    {
                        Debug.WriteLine("Name: " + myLookupItem.Key);
                        Debug.WriteLine("Id: " + myLookupItem.ToString());
                    }

Problem is that the

myLookupItem.ToString()

doesn't display actual value, instead only System.Linq.Lookup2[System.String,System.Int32] is displayed.

Later on, I should get the lookup value using lambda:

 int lookupValue = myLookup.Where(x => x.Key == "Test").Select(x => x).FirstOrDefault());

but this also gives the same as above.

Please advise how to achieve this.

Thanks in advance.

Answer

miguel.hpsgaming picture miguel.hpsgaming · Dec 13, 2011

That's because the lookup item is a collection. You can see every value of the lookup like this:

foreach (var myLookupItem in myLookup)
{
    Debug.WriteLine("Key: " + myLookupItem.Key);
    foreach (var myLookupValue in myLookupItem)
    {
        Debug.WriteLine("Value: " + myLookupValue);
    }
}