Search code examples
c#linqaggregateanonymous-types

C# return a single aggregated value using LINQ


I'm want to acquire a total from an IEnumerable collection class using LINQ.

A condensed version of my collection class is:

    public class BrokerCcyValue
    {
        public string BrokerCode;
        public string CCY;
        public double Value;
    }

    public class BrokerCcyValues
    {
        private List<BrokerCcyValue> _items;

        public BrokerCcyValues()
        {
            _items = new List<BrokerCcyValue>();
        }

...some methods to add/modify _items, then...

        public double SumForCcy(string cCCY)
        {
            var a = (from item in _items.AsEnumerable()
                     where item.CCY == cCCY
                     group item by item.CCY into grp
                     select new
                     {
                         SumValue = grp.Sum(i => i.Value)
                     });
            return (double)a.SumValue;
        }
    }

I've followed examples online to create the LINQ statement. The design time error I'm getting on the final return (double)a.SumValue; is CS1061: 'IEnumreable<>' does not contains a definition for 'SumValue' as no accessible extension method 'SumValue' accepting a first argument of type 'IEnumreable<>' could be found.

How do I get SumValue out of the anonymous type I've declared? Do I even need an anonymous type?


Solution

  • You don't need to use gruop by, you can use directly the sum method.

    public double SumForCcy(string cCCY)
    {
        return _items.Where(item => item.CCY == cCCY).Sum(i => i.Value);
    }
    

    In your original quetion a has type IEnumerable<>, which is not convertible to double. You have to call at least FirstOrdeFault()?.SumValue ?? 0 to get result.