简体   繁体   中英

I've just upgraded from a VS2010 project, but my linq query now won't sum an anonymous type

When I compile the following code I get an error "System.Linq.Grouping AnonymousType#1 does not contain a definition for sum"

The error appears where Networth sums g. If I put a value like 0 in for the Networth the rest of the query is fine.

public static System.Collections.Generic.List<EBookLogic.NetworthYearSummary> GetNetworthProjectionSummary(System.Guid ebookId, out decimal targetNetWorth, out int targetAge)
    {
        targetNetWorth = 0m;
        targetAge = 0;
        System.Collections.Generic.List<EBookLogic.NetworthYearSummary> values = null;
        using (TrulityEntities ent = new TrulityEntities())
        {
            EBook eb = ent.EBooks.FirstOrDefault((EBook e) => e.EBookID == ebookId);
            if (eb != null)
            {
                targetNetWorth = (eb.TargetedNetworth ?? 0m);
                targetAge = (int)(eb.TargetAge ?? 0);
            }
            IOrderedQueryable<EBookLogic.NetworthYearSummary> result = 
                from t1 in ent.vwNetworthProjectionSummaries
                where t1.EBookID == ebookId
                group new
                {
                    t1
                } by t1.FinancialYear into g
                select new EBookLogic.NetworthYearSummary
                {
                    FinancialYear = (int)g.Key,
                    NetWorth = g.Sum((<>f__AnonymousType1<vwNetworthProjectionSummary> p) => p.t1.TotalAssets ?? (((decimal?)0m - p.t1.TotalLiabilities) ?? 0m))
                } into n
                orderby n.FinancialYear
                select n;
            values = result.ToList<EBookLogic.NetworthYearSummary>();
        }
        return values;

    }

The problem is with the decompiler I was using, the syntax should have been:

NetWorth = g.Sum(p => 

No need to cast it.

Just to throw in my three cents to your answer (where you saying you used a decompiler)... When you are using an anonymous type the compiler creates a new type on your behalf. The type is an ordinary CLR type. It's however decorated with an unspeakable name so they cannot be invoke from user code. What happened in your case is that the decompiler met the type and used the name it encountered. I'm guessing in the decompiled code there was also a <>f__AnonymousType1 type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM