2011-07-08 28 views
1

如何讀取以外的查詢變量,如果範圍並進一步使用它。如何訪問查詢變量

If (IsPaymentList) 
{ 
      var query = paymentList.GroupBy(
      grp => (grp.GrouByField), 
      (GrouByField, paymentListgroup) => new 
      { 
       Key = GrouByField, 
       receiptAmount = paymentListgroup.Sum(fields => fields.PaymentAmount), 
       creditAccountnumber = paymentListgroup.Max(fields => fields.CreditAccountNumber), 
       bankAccountName = paymentListgroup.Max(fields => fields.AccountName), 
       bankName = paymentListgroup.Max(fields => fields.BankName), 
       payCurrency = paymentListgroup.Max(fields => fields.PaymentCurrencyID), 
       partnerServiceID = paymentListgroup.Max(fields => fields.PartnerServiceID), 

      }); 
} 

有人請分享您的經驗。 謝謝

+1

不可能的,如果你可以使用var – V4Vendetta

+0

我能想到的最乾淨的解決方案是使用命名類型。 – CodesInChaos

+0

這與查詢無關,但基本的編程知識。請查找範圍:http://en.wikipedia.org/wiki/Scope_%28computer_science%29 – RvdK

回答

0

可以聲明查詢變量類型的 IQueryable<IGrouping<typeOfKey,typeOfSelect>> query = null; 外,如果將其設置爲空,其中typeOfKey是grp.GrouByField屬性的類型。而不是選擇一個匿名類型,你必須創建一個具有需要這樣的屬性的新類:

public class NewClass 
{ 
    public int Key {get;set;} 
    public decimal ReceiptAmount {get;set;} 
    //add all the properties here 

    public NewClass(string key,decimal recieptAmount) 
    { 
      //and add constructor for all the needed properties 
    } 
} 

在創建類集合查詢到的泛型類型

//i used int for your grp.GrouByField type 
IQueryable<IGrouping<int,NewClass>> query = null; 
if(IsPaymentList) 
{ 
    query = paymentList.GroupBy(
      grp => (grp.GrouByField), 
      (GrouByField, paymentListgroup) => 
      new NewClass(GrouByField, 
      paymentListgroup.Sum(fields => fields.PaymentAmount), 
      paymentListgroup.Max(fields => fields.CreditAccountNumber), 
      paymentListgroup.Max(fields => fields.AccountName), 
      paymentListgroup.Max(fields => fields.BankName), 
      paymentListgroup.Max(fields => fields.PaymentCurrencyID), 
      paymentListgroup.Max(fields => fields.PartnerServiceID))); 
} 
1

你需要做的是將查詢變量移出if語句的上下文。

這是你如何做到這一點與整數列表的示例:

var list = new [] { 10, 3, 2, 4, 6, 7, 8 }; 

var condition = false; 

IEnumerable<IGrouping<int,int>> query; 

if(condition) 
{ 
    query = list.GroupBy(x => x); 
} 

然後我可以在if語句之後繼續查詢query變量這樣的,如果我那麼喜歡:

query.Take(2)

現在的問題是,您想在創建範圍之外使用query變量。

考慮以下幾點:

static void Main(string[] args) 
{ 
    var x = 10; 

    { 
     var y = 20; 
    } 

    Console.WriteLine(x+y); 
} 

這不會編譯,因爲y是在另一個範圍比x,通過移動y之外的範圍的decleration解決這個問題。就像這樣:

var x = 10; 
int y; 
{ 
    y = 20; 
} 

Console.WriteLine(x+y); 

在這種情況下,宣佈y時,您不能使用var,因爲這將意味着,你也告訴編譯器它是什麼樣的類型。而你不是。所以編寫var y;沒有任何意義,但是var y = 10;的確如此,因爲現在編譯器知道這實際上是一個整數。

+0

現在你失去了靜態類型的查詢' – CodesInChaos

+0

我知道,更新我的答案.. –

+0

@CodeInChaos,更好的? –