-1

Let's say I have an object that looks like this:

private class Group
{
    public int id { get; set; }
    public string name { get; set; }
    public int memberCount { get; set; }
}

And then I have a List<Group> called groups. But, now what I need is just a list of all of the names.

List<string> names = group.???

So, just to be clear, if groups looks like this:

id    name        memberCount
-----------------------------
1,   "Math Club",    24
2,   "Chess Club",   12
3,   "Drama Club",   19

Then what I want is a list that looks like this:

"Math Club"
"Chess Club"
"Drama Club"
2
  • 2
    groups.Select(g => g.name) Commented Oct 10, 2017 at 14:39
  • for future reference object is a class that all other classes inherit from, therefore and you can actually have a List<object>, which is not the exact same as a List<SomeOtherClass> Commented Oct 10, 2017 at 14:52

3 Answers 3

4

Just use LINQ:

List<string> names = groups.Select(x => x.name).ToList();

This will Select() all the names, and turn it into a List<string> via ToList()

Sign up to request clarification or add additional context in comments.

Comments

3

Use LINQ and Select method:

var Names = groups.Select(c => c.name).ToList();

Comments

1

Non Linq answer

List<string> names = new List<string>();
foreach(var group in groups)
{
    names.Add(group.name);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.