Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
I have a
List<Dictionary<string, object>>
with values like this:
{ name: "Joe", age: 23, ... },
{ name: "Jack", age: 19, ... },
I want to create a List<string>
from that which holds the names.
How would I do this (along with the cast)?
I know how to select out the values by name, but how do I use a lambda to return the name
field and cast it to string for the list?
Is this right?
List<string> names = objects.Select(
item => item[ "name" ].ToString()
).ToList<string>();
–
–
–
However, if I may make a suggestion, you shouldn't use Dictionaries this way. Consider making a class for the data you have in your Dictionary.
class Person
public string Name { get; set; }
public int Age { get; set; }
// etc
–
Since the values are stored in a dictionary the key might not necessarily exist. To guard against KeyNotFoundException
use Dictionary(TKey, TValue).TryGetValue(TKey, TValue)
.
var objects = new List<Dictionary<string, object>>
new Dictionary<string, object>
{"name", "Foo"}
new Dictionary<string, object>
{"name", "Bar"}
new Dictionary<string, object>
{"blah", "Baz"}
// C# Local function
IEnumerable<string> GetName(IDictionary<string, object> obj)
// C# 7 out variable
if (obj.TryGetValue("name", out var name))
yield return name as string;
// ["Foo", "Bar"]
var names =
objects
.SelectMany(GetName)
.ToList();
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.