Home > Blockchain >  One line code of List<Dictionary<string, object>> to List<string>
One line code of List<Dictionary<string, object>> to List<string>

Time:04-05

Is there a shortest way to do this. Because I want to get only a certain key from dictionary

   List<Dictionary<string, object> channel = DatabaseFunction.Select(some parameter);
   List<string> result = new List<string>();
   
   for (int i = 0; i < channel.Count; i  )
   {
       result.Add(channel[i]["key"].ToString());
   }

CodePudding user response:

Assuming that "key" always exists in all Dictionary<String,Object> objects in channel and always has a non-null object reference:

List<String> result = channel
    .Select( dict => dict["key"].ToString() )
    .ToList();

A safer version, which skips-over dictionary elements without "key" and/or when the inner Object is null would be:

List<String> result = channel
    .Select( dict => ( ok: dict.TryGetValue( "key", out Object? obj ), obj ) )
    .Where( t => t.ok && t.obj != null )
    .Select( t => t.obj!.ToString() )
    .ToList();

CodePudding user response:

You can use Select instead of for loop

List<Dictionary<string, object> channel = DatabaseFunction.Select(some parameter);
List<string> result = channel.Select(item => item["key"].ToString()).ToList()

You can have the key check before adding it to the list with Where for safety

List<Dictionary<string, object> channel = DatabaseFunction.Select(some parameter);
List<string> result = channel
             .Where(dict => dict.ContainsKey("key"))
             .Select(item => item["key"].ToString()).ToList()

CodePudding user response:

List<string> results = new List<string>(channel.Keys);
  •  Tags:  
  • c#
  • Related