How can i convert a Model.Tag (has Id and Name) to a "List of" Name?
public List<string> TagNameList (int objectId)
{
List<string> tagNameList = db.Tags.Where(ob => ob.Id == objectId).ToList();
}
db.Tags.Where(ob => ob.Id 开发者_如何学Go== objectId).ToList();
I'm going into the db
context in the Tags
and i select all the tags that have a set objectId
via a navigation property i have setup through an ObjectTags
table that stores the relationships in two columns, both make up a composite key.
The sample returns an IQueryable<app.Models.Tag>
. Is there any quick way to convert this to a List<string>
with just the Tag.Name
?
Yup, you just need to apply a projection using Select
:
public List<string> TagNameList (int objectId)
{
return db.Tags.Where(ob => ob.Id == objectId)
.Select(tag => tag.Name)
.ToList();
}
EDIT: Okay, given your update, you can use First()
if you only want the first object from each collection - if you want the name from each object in the collection, you could use SelectMany
:
public List<string> TagNameList (int objectId)
{
return db.Tags.Where(ob => ob.Id == objectId)
.SelectMany(ob => ob.Tags)
.Select(tag => tag.Name)
.ToList();
}
Found the solution thanks to a good friend.
db.Objects.Where(ob => ob.Id == objectId).First().Tags.Select(t => t.TagName).ToList()
The First() was essential to "narrow" it down to one object and then navigate to the other table.
This is SO COOL. You could navigate to tens of tables like this. I wonder if you can write the longest line of code this way :D
精彩评论