2013-06-27 68 views
5

我想2列出了從這些組合:如何合併返回匿名類型的lambda表達式的LINQ查詢?

var quartEst = Quarterly_estimates 
.OrderByDescending (q => q.Yyyy) 
.ThenByDescending (q => q.Quarter) 
.Where (q => 
    q.Ticker.Equals("IBM") 
    && 
    q.Eps != null 
    ) 
.Select (q => new { 
    ticker = q.Ticker, 
    Quarter = q.Quarter, 
    Year = q.Yyyy, 
    Eps = q.Eps}) 
.AsEnumerable() 
.Where (q => Convert.ToInt32(string.Format("{0}{1}", q.Year, q.Quarter)) > Convert.ToInt32(finInfo)); 

var quartAct = Quarterlies 
.OrderByDescending (q => q.Yyyy) 
.ThenByDescending (q => q.Quarter) 
.Where (q => 
    q.Ticker.Equals("IBM") 
    && 
    Convert.ToInt16(q.Yyyy) >= DateTime.Now.Year - 3 
    ) 
.Select (q => new { 
    Tick = q.Ticker, 
    Quarter = q.Quarter, 
    Year = q.Yyyy, 
    Eps = q.Eps_adj}) 
.AsEnumerable() 
.Where (q => Convert.ToInt32(string.Format("{0}{1}", q.Year, q.Quarter)) <= Convert.ToInt32(finInfo)); 

我得到的錯誤一個簡單的聯合命令:

var quartComb = quartEst.Union(quartAct); 

這裏的錯誤:

Instance argument: cannot convert from 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Linq.IQueryable<AnonymousType#2>' 

怎麼辦我需要做些什麼來實現這種合併?

回答

6

要使用Union方法,集合必須具有相同的類型。爲了使兩個匿名類型被視爲相同,它們必須具有完全相同類型的完全相同的成員。

試試這個:

var quartEst = Quarterly_estimates 
    ... 
    .Select (q => new { 
     Tick = q.Ticker,  // renamed ticker to Tick 
     Quarter = q.Quarter, 
     Year = q.Yyyy, 
     Eps = q.Eps}) 
    ... 

var quartAct = Quarterlies 
    .Select (q => new { 
     Tick = q.Ticker, 
     Quarter = q.Quarter, 
     Year = q.Yyyy, 
     Eps = q.Eps_adj}) 
    ... 

var quartComb = quartEst.Union(quartAct); 
+1

1+或重命名股票於北京時間? – Olrac

+0

@Olly yep,那也可以。只要名稱相同,名稱是什麼都沒有關係。 –

0

要投你必須將它轉換爲動態兩種不同的匿名類型,這是下面的代碼

protected void Page_Load(object sender, EventArgs e) 
    { 
     List<AlertInfo> alert = new List<AlertInfo>(); 
     alert.Add(new AlertInfo() { StratId = 1, GroupId = 1 }); 
     alert.Add(new AlertInfo() { StratId = 1, GroupId = 2 }); 
     alert.Add(new AlertInfo() { StratId = 1, GroupId = 3 }); 
     alert.Add(new AlertInfo() { StratId = 2, GroupId = 1 }); 
     alert.Add(new AlertInfo() { StratId = 2, GroupId = 2 }); 
     alert.Add(new AlertInfo() { StratId = 2, GroupId = 3 }); 
     alert.Add(new AlertInfo() { StratId = 3, GroupId = 1 }); 
     alert.Add(new AlertInfo() { StratId = 3, GroupId = 2 }); 

     //To know how much data will get stored 
     var totalDataStore = alert.Select(x => x.StratId).Distinct().ToList(); 

     var result = alert.Where(x => x.StratId == 1).Select(x => new { Data1 = "Group" + x.StratId + x.GroupId }).Cast<dynamic>().Union(alert.Where(y => y.StratId == 2).Select(y => new { Data2 = "Group" + y.StratId + y.GroupId })).ToList(); 

    } 
} 

public class AlertInfo 
{ 
    public int StratId { get; set; } 
    public int GroupId { get; set; } 
}