My GUI is calling a service project that does some linq work, and returns data to my GUI. However, I am battling with the return type of the method. After some reading, I have this as my method:
public static IEnumerable GetDetailedAccounts()
{
IEnumerable accounts =(from a in Db.accounts
join i in Db.financial_institution on
a.financial_institution.financial_institution_id
equals i.financial_institution_id
join acct in Db.z_account_type on a.z_account_type.account_type_id
equals acct.account_type_id
orderby i.name
select new
{
account_id = a.account_id,
name = i.name,
description = acct.description
});
return accounts;
}
However, my caller is battling a bit. I think I am screwing up the return type, or not handling the caller well, but it’s not working as I’d hoped.
This is how I am attempting to call the method from my GUI.
IEnumerable accounts = Data.AccountService.GetDetailedAccounts();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Accounts:");
Console.ForegroundColor = ConsoleColor.White;
foreach (var acc in accounts)
{
Console.WriteLine(string.Format("{0:00} {1}", acc.account_id, acc.name + " " + acc.description));
}
int accountid = WaitForKey();
However, my foreach, and the acc – isn’t working. acc doesn’t know about the name, description and id that I setup in the method. Am I at least close to being right?
@BrokenGlass is correct that the root of the issue is that you’re using an anonymous type. That results in you using the non-generic version of IEnumerable which doesn’t know what type the objects are.
Rather than using
dynamicthough (which requires .NET 4.0 which may or may not be an issue for you), I would recommend creating an actualAccountclass.That way you can return an
IEnumerable<Account>instead of justIEnumerable. Then you’ll be able to use the properties since it knows that it’s an Account.Once you create the Account class your method then becomes:
Then the calling code can remain the same.
I thought I should point out that
vardoesn’t work the way you probably think it does. The type of the variable is still determined compile-time, which means (for the most part) it’s just a shortcut. Your example would be identical to if you had usedobjectinstead ofvarbecauseIEnumerablecan only containobject.If you’re working in .NET I’d recommend follow .NET naming conventions though so
AccountIdinstead ofaccount_idbut that won’t affect whether it works or not.