I have this property, which is working fine:
public IEnumerable<IGrouping<MessageType, Message>> MessageGroups
{
get
{
return
(from msg in _messages
orderby msg.Type descending
group msg by msg.Type);
}
}
However, it’s causing me to have to repeat the ugly-looking IEnumerable<IGrouping<MessageType, Message>> in several places in my code. I tried to make this easier on the eyes by defining a trivial wrapper interface like this:
public interface IMessageGroups :
IEnumerable<IGrouping<MessageType, Message>> { }
and changing the property above to:
public IMessageGroups MessageGroups
{
get
{
return
(IMessageGroups)
(from msg in _messages
orderby msg.Type descending
group msg by msg.Type);
}
}
This builds fine, but at runtime I get:
Unable to cast object of type
‘System.Linq.GroupedEnumerable`3[Message,MessageType,Message]’
to type ‘IMessageGroups’.
(project-specific namespaces removed from the error message)
What can I do to fix this?
You could try using a type alias:
And then:
Another possibility is to expand further your LINQ query and select some custom type you create after the grouping:
and Foo:
If you don’t care about lazy evaluation you could put a
.ToArray()at the end of your LINQ query and the return type becomes simplyFoo[].