简体   繁体   中英

Filter List<object> for Dictionary<string,?> and Get First Key

I have a IList<object> which contains a list of string , Dictionary<string, string[]> or Dictionary<string, object> . I would like to get the first string of each Dictionary .

I've tried:

var firstStrings =
    list
    .Where(x => !(x is string))
    .Select(x => ((Dictionary<string, object>)x).Keys.ElementAt(0))
    .ToArray();

But I get the error

System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.Dictionary 2[System.String,System.Collections.Generic.List 1[System.String]]' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

As the error states, you can't cast a Dictionary<string, string[]> to a Dictionary<string, object> . One way to do what you want is to cast to IDictionary (and use OfType instead of the Where clause for better type safety:

var firstStrings =
    list.OfType<IDictionary>()
        .Select(x => x.Keys
                      .OfType<object>()
                      .First()
                      .ToString()
               )
        .ToArray();

You may need to add using System.Collections; to your using block since IDictionary is in a different namespace than the generic class.

One other note - dictionaries are not ordered, so the "first" element is arbitrary (adding a new key/value pair may change the "first" key you get back).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM