Reputation: 48696
I have the following code:
private void EntryBrowserLoad(object sender, EventArgs e)
{
var ase = new AprilShowersEntities();
var q =
from d in ase.Entries
orderby d.EntryEndTime
select d;
var dateQuery = from d in q.AsEnumerable()
select new
{
d.EntryEndTime,
d.EntryId,
d.EntryPlainText,
d.EntryStartTime,
d.EntryText,
EntryHeader = GetEntry(d.EntryEndTime, d.EntryPlainText)
};
lcEntries.DisplayMember = "EntryHeader";
lcEntries.DataSource = dateQuery;
}
private void BtnOkClick(object sender, EventArgs e)
{
var q = (Entry) lcEntries.SelectedItem.Value; // Error here on this line
MessageBox.Show(q.EntryText);
}
My problem is its getting an error on the line marked above, complaining about not being able to cast the object back into an Entry object. The reason, I'm sure, is because I'm using select new
in my LINQ query. My question is, how can I read the EntryText property of the returned SelectedItem.Value object?
Upvotes: 2
Views: 871
Reputation: 126884
You are projecting into an anonymous type. To reference the result elsewhere (outside of the context of the containing method) with compile-time safety and features such as Intellisense, you need to project into a concrete type. If you do not already have such a class, then define a class that describes your element
class TheEntry { /* define properties */ }
Then select into the class with your query
select new TheEntry
And then you can cast to that that class
var entry = (TheEntry)lcEntries.SelectedItem.Value;
It is generally preferred to define a proper type once you start passing a query result around or need access to it outside of its containing method. However, you can technically bypass this by using dynamic or runtime binding, as well. I would not recommend it, but it is an available approach.
dynamic entry = lcEntries.SelectedItem.Value;
MessageBox.Show(entry.EntryText); // no compile-time support, purely runtime
Upvotes: 6