gpt4 book ai didi

c# - Linq 和返回类型

转载 作者:太空狗 更新时间:2023-10-30 01:10:28 25 4
gpt4 key购买 nike

我的 GUI 正在调用一个执行一些 linq 工作的服务项目,并将数据返回到我的 GUI。但是,我正在与方法的返回类型作斗争。阅读之后,我将此作为我的方法:

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;
}

然而,我的来电者有点挣扎。我想我搞砸了返回类型,或者没有很好地处理调用者,但它没有像我希望的那样工作。

这就是我尝试从我的 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();

但是,我的 foreach 和 acc - 不工作。 acc 不知道我在方法中设置的名称、描述和 ID。我是否至少接近于正确?

最佳答案

@BrokenGlass 是正确的,问题的根源是您使用的是匿名类型。这会导致您使用 IEnumerable 的非通用版本,它不知道对象是什么类型。

而不是使用 dynamic虽然(这需要 .NET 4.0,这对你来说可能是也可能不是问题),但我建议创建一个实际的 Account类。

这样你就可以返回一个 IEnumerable<Account>而不仅仅是 IEnumerable .然后您就可以使用这些属性,因为它知道这是一个帐户。

一旦您创建了 Account 类,您的方法就变成了:

public static IEnumerable<Account> GetDetailedAccounts()
{
IEnumerable<Account> 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 {account_id = a.account_id, name = i.name, description = acct.description});
return accounts;

}

那么调用代码可以保持不变。

我想我应该指出 var并不像您认为的那样工作。变量的类型仍然是编译时确定的,这意味着(在大多数情况下)它只是一个快捷方式。如果您使用了 object,您的示例将是相同的而不是 var因为IEnumerable只能包含 object .

如果您在 .NET 中工作,我建议您遵循 .NET 命名约定 AccountId而不是 account_id但这不会影响它是否有效。

关于c# - Linq 和返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4632595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com