I would like to add an orderby when I call Load() in the following example:
(Note: This object has an EF Article that has been loaded somewhere else)
private string GetTags()
{
var tags = this.Article.tags;
if (!tags.IsLoaded && this.Article.EntityState != EntityState.Detached)
{
tags.Load();
tags.OrderBy(t => t.name);
}
StringBuilder result = new StringBuilder();
foreach (var tag in tags)
{
result.Append(tag.name).Append(" ");
}
return result.ToString();
}
The problem is this is not sorting the tags in alphebetical order. What am I missing?
Like most other LINQ methods,
OrderBydoesn’t affect the underlying query, which is immutable. You have to do something with the value it returns:The problem is,
tagsis not an IEnumerable or IQueryable: it is an EntityCollection. So the above statement won’t work very well. Furthermore, your method name (GetTags) doesn’t very well indicate that you’re going to be modifying the order of the tags on theArticleobject, so it might be better to just keep theOrderBylocal, and do it again each time someone callsGetTags: