C# 查询linq中的Foreach
我在我的Domain.Services项目上有以下方法C# 查询linq中的Foreach,c#,linq,C#,Linq,我在我的Domain.Services项目上有以下方法 public IList GetGroupProduct(IPrincipal user, int year) { if (user == null) { throw new ArgumentException("user"); } var query = (from p in _repository.GetRevenues()
public IList GetGroupProduct(IPrincipal user, int year)
{
if (user == null)
{
throw new ArgumentException("user");
}
var query = (from p in _repository.GetRevenues()
join o in _repository.GetEquipments() on p.IdEquipment.Equipment_Id equals
o.Equipment_Id
join c in _repository.GetGroupEquipment() on o.IdGroup.Group_Id equals
c.Group_Id
where p.DateTimeCreationData.Year == year
orderby p.DateTimeCreationData
select new
{
p.Quantity,
p.Value,
c.NameGroup
}).ToList();
return query;
}
在我看来,我呼吁
var listGroupProductsActualYear = receitaServico.GetGroupProduct(User, DateTime.Now.Year);
这很好,但要完成结果太难了。我不知道最好的方法是返回IList还是其他类型
如何在这个返回GetGrupoProduto方法的变量中执行foreach
或者我如何才能做出更好的方法,也许不使用IList
另一种方法,返回键入的
public IEnumerable<Revenue.Revenue> GetRevenues(IPrincipal user, int year)
{
if (user == null)
{
throw new ArgumentException("user");
}
return from p in _repository.GetRevenues()
where p.DateTimeCreationData.Year == year
orderby p.DateTimeCreationData
select p;
}
public IEnumerable GetRevenues(IPrincipal用户,整数年)
{
if(user==null)
{
抛出新的ArgumentException(“用户”);
}
从_repository.GetRevenues()中的p返回
其中p.DateTimeCreationData.Year==年
orderby p.DateTimeCreationData
选择p;
}
您可以使用动态
功能
foreach(dynamic item in listaGruposProdutosAnoAtual)
{
var quantity = item.Quantidade;
}
但我强烈建议您使用命名类型,而不是匿名类型,因为这种方式不是类型安全的。如果您不想使用非泛型集合类型或接口(在大多数情况下,您不想),则必须创建一个新类型以用作返回类型(或者使用dynamics,但它几乎同样糟糕)
公共类MyReturnType
{
公共类型a{get;set;}
公共b类型{get;set;}
公共CType c{get;set;}
}
公共IList GetGroupProduct(IPrincipal用户,国际年)
{
...
选择新的MyReturnType
{
a=。。。,
b=…,。。。,
c=。。。
}).ToList();
}
简单的方法是:不要使用匿名类型,使用命名类型,然后从方法中返回IList
,读取代码比必须要困难。看一看。@Selman22我在另一个方法中完成了它,在这个方法中我返回了特定的域,但是在这个新的例子中,我加入了2个。我需要为这个做一个新域名吗?@nvoigt我做了英文更正你说的“域名”是什么意思?你不需要额外的edmx,只需要一节普通课。然后,代替select new{..}
你做一个select new Yourtype(){..}
但是在这种情况下,要做一个命名类型,我需要创建另一个域来处理这个问题?@Lucas_Santos创建一个新类来保存这个信息需要10秒钟的时间。
public class MyReturnType
{
public AType a {get; set;}
public BType b {get; set;}
public CType c {get; set;}
}
public IList<MyReturnType> GetGroupProduct(IPrincipal user, int year)
{
...
select new MyReturnType
{
a=...,
b=...,
c=...
}).ToList();
}