Hi all, I'm getting my feet wet with object-oriented programming. I've put together an object that loads agents based off of their employee number. One of the items there is an anonymous list generated from a Linq query. I cannot access the individual list items after creating the objects. Here's the code:
foreach (var v in query)
{
for (int j = 0; j < aObject.Count(); j++)
{
aObject[j] = new SubmittedExceptions(Convert.ToInt32(v.Employee_Number));
}
}
(where query is the results from another Linq query to get a full list of employee numbers).
So the question is, how do I access the individual items under aObject[x].stats? I need to fill some on-screen data with stats.Full_Name and stats.Supervisor_Name. I tried:
Code
foreach (var v in aObject[x].stats)
{
lblEmployee_Number.txt = v.Full_Name;
}
but v.full_name (nor anything else under the anonymous type 'stats' is recognized. HELP
Thanks in advance for the help!
3 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Sam HobbsRank #107 · 20.5K reputationPosted Nov 12, 2009, 9:04 PM EST
✓ Accepted answer0
You cannot. A method cannot return an anonymous type, since the strong typing ("individual items") of the anonymous type is lost. See Anonymous Types (C# Programming Guide), which says:
"If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type."
Thanks. That makes sense. I was thinking the anonymous type would be a great way to store some LINQ data in my object. Looks like i'm going to have to have to do some translation in an intermediate layer then pass that up to the base object.
Thanks for the help.
0
Sam HobbsRank #107 · 20.5K reputationPosted Nov 13, 2009, 7:17 AM EST
0
I certainly don't like anonymous types. It can be very frustrating to determine what type something is when I do need to specify a type. I prefer to invest the time in writing code that specifies a type explicitly. Isn't that more object-oritented?
Sam HobbsRank #107 · 20.5K reputationPosted Nov 12, 2009, 9:04 PM EST
"If you must store your query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type."
shawn3 reputationPosted Nov 13, 2009, 7:02 AM EST
Thanks for the help.
Sam HobbsRank #107 · 20.5K reputationPosted Nov 13, 2009, 7:17 AM EST