How do I grab a single attribute from a Collection of objects that I group into a list?

I have two lists that I'm trying to join based on a Group => ID and Artist => GroupID.

When I show groups, I want to show all the members in the group from the Artists list.

            var groupID = from Group in allGroups
                          join Artist in allArtists
                          on Group.Id equals Artist.GroupId
                          into Members
                          where Group.Id == id
                          select new
                          {
                              Group = Group.GroupName,
                              Members
                          };
            return Json(groupID);

When the JSON data renders in the browser, I get all the data from each artist and I just want to show the name. See below:

[{"group":"G-Unit","members":[{"artistName":"Lloyd Banks","realName":"Christopher Lloyd","age":34,"hometown":"New York City","groupId":2,"group":null},{"artistName":"The Game","realName":"Jayceon Taylor","age":37,"hometown":"Compton","groupId":2,"group":null},{"artistName":"50 Cent","realName":"Curtis Jackson","age":41,"hometown":"New York City","groupId":2,"group":null}]}]

Thanks in advance for your help!

1 answer

  • answered 2018-01-11 20:46 Adam Brown

    This should work...

    var groupID = from Group in allGroups
                          join Artist in allArtists
                          on Group.Id equals Artist.GroupId
                          into Members
                          where Group.Id == id
                          select new
                          {
                              Group = Group.GroupName,
                              Members = Members.Select(e => e.artistName)
                          };
            return Json(groupID);