2014-09-02 54 views
-1

我有以下方法對我Domain.Services項目的foreach在查詢LINQ

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或其他類型。

enter image description here

我怎樣才能做一個foreach在這個變量有我GetGrupoProduto方法的返回?

或者我該如何做出更好的方法,可能不會使用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; 
    } 
+2

最簡單的方法是:不使用匿名類型,使用名爲類型的,從你的方法 – 2014-09-02 13:47:52

+0

返回IList的''讀你的代碼是難度比它必須是。看看[這裏](http://meta.stackoverflow.com/questions/266563/do-non-english-words-increase-the-probability-of-receiving-downvotes)。 – nvoigt 2014-09-02 13:49:09

+0

@ Selman22我用另一種方法做了它,在那裏我返回了特定的域,但在這種新的情況下,我做了2次連接。我需要爲此做一個新的域名? – 2014-09-02 13:49:43

回答

0

可以使用dynamic功能

foreach(dynamic item in listaGruposProdutosAnoAtual) 
{ 
    var quantity = item.Quantidade; 
} 

但我higly建議您使用一個命名的類型,而不是匿名類型因爲這種方式不是型號安全

+0

但是在這種情況下,要做一個命名類型,我需要創建另一個域只是fot這種情況? – 2014-09-02 13:56:40

+0

@Lucas_Santos這將需要你10秒鐘的時間來創建一個新的類來保存這些信息。 – Servy 2014-09-02 14:17:31

0

如果您不想使用非泛型集合類型或接口(並且在大多數情況下您不想使用),則必須創建一個新類型以用作返回類型(或使用動態,但它幾乎一樣糟糕)。

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