sara brown
sara brown

Reputation: 1067

no definition Keys c#

foreach (string myKey in mySortedList.Keys)

why it says does not contain definition Keys and no extension Keys. may i know why? i already using System.Collections.Generic;

Upvotes: 0

Views: 96

Answers (3)

Michael
Michael

Reputation: 9044

Maybe an example will help. In the code below, the first foreach compiles, but the second doesn't. Both are based on the same instance of a SortedList, but the second one casts it as a different type, which does not support Keys.

        SortedList<string, string> sorted = new SortedList<string, string>();

        foreach (string s in sorted.Keys)
            Console.WriteLine(s);

        IEnumerable stillSorted = sorted as IEnumerable;

        foreaach (string t in stillSorted.Keys)
            Console.WriteLine(t);

Is this your problem? If you are being passed an object, try casting it yourself as in the example below:

        SortedList<string, string> sorted = mySortedList as SortedList<string, string>;
        if (sorted != null)
            foreach (string s in sorted.Keys)
                Console.WriteLine(s);

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124692

whatever mySortedList actually is, it has no property Keys. The compiler told you that much. So:

  1. Determine the type of mySortedList.
  2. Go to MSDN, consult documentation.
  3. Profit.

Upvotes: 2

Alex
Alex

Reputation: 35409

Either mySortedList is not a SortedList or it hasn't been un-boxed from it's more primitive state.

var list = mySortedList as SortedList;

foreach (string myKey in list.Keys) { ... }

http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx

Upvotes: 0

Related Questions