web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

How to calculate sum of column value from entity collection?

(0) ShareShare
ReportReport
Posted on by 483

Hello,

How to calculate sum of column value from entity collection in c#? Pls suggest how can we do it in c# in a simpler way?

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Macoy Profile Picture
    275 on at

    Hi Krishna,

    You can achieve this using FetchExpression aggregation. See sample below:

    // Fetch the sum of estimatedvalue for all opportunities.  This is the equivalent of

    // SELECT SUM(estimatedvalue) AS estimatedvalue_sum ... in SQL.

    string estimatedvalue_sum = @"

    <fetch distinct='false' mapping='logical' aggregate='true'>

       <entity name='opportunity'>

          <attribute name='estimatedvalue' alias='estimatedvalue_sum' aggregate='sum' />

       </entity>

    </fetch>";

    EntityCollection estimatedvalue_sum_result = _serviceProxy.RetrieveMultiple(new FetchExpression(estimatedvalue_sum));

    foreach (var c in estimatedvalue_sum_result.Entities)

    {

       decimal total= ((Money)((AliasedValue)c["estimatedvalue_sum"]).Value).Value;

       System.Console.WriteLine("Sum of estimated value of all opportunities: " + total);

    }

    System.Console.WriteLine("just a sample");

    Regards,

    Macoy

  • dkrishna Profile Picture
    483 on at

    I want to do sum from c# code and not from fetch xml. Pls suggest for this.

  • Alex Fun Wei Jie Profile Picture
    33,628 on at

    Hi Krishna prasad,

    which method did you use for retrieve, query expression? fetchxml ? please elaborate.

  • dkrishna Profile Picture
    483 on at

    To retrieve entity collection i use fetch xml but in that i dont want to use aggregate function in fetch xml. I want to do sum of field from code once i got collection.

  • Suggested answer
    Macoy Profile Picture
    275 on at

    Hi Krishna,

    My given sample is applicable for c#. FetchExpression is one type of query you can use instead of QueryExpression.

    Regards,

    Macoy

  • Suggested answer
    Alex Fun Wei Jie Profile Picture
    33,628 on at

    Hi,

    try this, the below example i am using Money field.

    EntityCollection ec = ExecuteFetch(fetchXmlString);

    if (ec.Entities.Count > 0)

    {

       //declare a variable here

       double total =0;

       foreach (var item in ec.Entities)

      {

           if (item.Attributes.Contains("fieldschemaname"))

         {

            total  +=((Money)item.Attributes["fieldschemaname"]).Value;

         }

      }

    }

  • dkrishna Profile Picture
    483 on at

    Can you pls suggest using linq to get sum and to avoid loop for every record if there are more records.

  • Suggested answer
    Temmy Wahyu Raharjo Profile Picture
    2,916 on at

    Actually linq also will loop based on the data also. :)

    var totalSum = result.Entities.Sum(e=> e.Contains("new_amount") ? e.GetAttributeValue<Money>("new_amount").Value : 0)

    if there are more records then you need to do this:

    var totalSum = 0;

    var query =new QueryExpression("yourentity");

    ..

    query.PageInfo = new PagingInfo

               {

                   Count = queryCount,

                   PageNumber = pageNumber,

                   PagingCookie = null,

                   ReturnTotalRecordCount = true

               };

    while (true)

    {

    var result = service.RetrieveMultiple(query);

    totalSum+ = result.Entities.Sum(e=> e.Contains("new_amount") ? e.GetAttributeValue<Money>("new_amount").Value : 0);

     if (result.MoreRecords)

                   {

                       query.PageInfo.PageNumber++;

                       query.PageInfo.PagingCookie = result.PagingCookie;

                   }

                   else

                   {

                       break;

                   }

    }

  • Vaibhav Shukla Profile Picture
    120 on at

    int total =0;

    EntityCollection ec = service.RetrieveMultiple(EntityName);

    foreach (var item in ec.Entities)

      {

           if (item.Attributes.Contains("primaryfieldname"))

    {

            total ++;

         }

      }

    }

  • dkrishna Profile Picture
    483 on at

    Thanks alot temmy It works !!!. can you pls also suggest if i had to add where condition same linq like casetype=700001 which is optionset value how i can add it?

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans