Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge LINQ querys of lambdas which return of anonymous type?

I'm trying to combine 2 lists from these:

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

I get the error for a simple Union command:

var quartComb = quartEst.Union(quartAct);

Here's the error:

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

What do I need to do to achieve this merge?

like image 870
inquisitive_one Avatar asked Jun 27 '13 02:06

inquisitive_one


1 Answers

To use the Union method, the collections must have the same type. In order for two anonymous types to be considered the same, they must have exactly the same members with exactly the same types.

Try this:

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);
like image 165
p.s.w.g Avatar answered Oct 18 '22 15:10

p.s.w.g