Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

LINQ to sum the items in a list

Posted on 2011-05-12
9
Medium Priority
?
540 Views
Last Modified: 2013-12-16
Hi,

 I have a list which is of object type.
 my list contains the set of elements like
 
    Jan  3 ,4 5 , 6
    feb   3, 5 ,7,8

 now i need to sum the values and display in my grid as

   Jan  3 ,4 5 , 6
    feb   3, 5 ,7,8
   total  6  9  12 14
             
  how can i sum those values using LINQ and display everything in the grid

 Thanks
0
Comment
Question by:ram27
  • 4
  • 3
  • 2
9 Comments
 

Author Comment

by:ram27
ID: 35748909
My property names in listobject as header s in the grid like

 
 RowHeader              pens           pencils      books        bags
  Jan                               3             ,4              5 ,           6
    feb                              3,              5 ,             7,           8

 
 Thanks
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35749547
If I understand your structure correctly, then I think you have something like this (for example):

List<Inventory> items = new List<Inventory>()
{
    new Inventory() { Month = "Jan", Pens = 3, Pencils = 4, Books = 5, Bags = 6 },
    new Inventory() { Month = "Feb", Pens = 3, Pencils = 5, Books = 7, Bags = 8 }
};

Open in new window


If so, you should be able to do something like this:

var totals = new
{
    Pens = items.Sum(item => item.Pens),
    Pencils = items.Sum(item => item.Pencils),
    Books = items.Sum(item => item.Books),
    Bags = items.Sum(item => item.Bags)
};

Open in new window


You should be able to data-bind the grid to that result. What kind of grid are you using?
0
 

Author Comment

by:ram27
ID: 35750801

 Thankyou,

 Is there is any way i can add the where condition,  becase i may get the the different values
 which i need to use in 3 differnt grids like below
 GRid 1:
 Current Statistics:

   RowHeader              pens           pencils      books        bags
  Jan                               3             ,4              5 ,           6
    feb                              3,              5 ,             7,           8

 
GRID 2:  
Moth Statistics

 RowHeader              pens           pencils      books        bags
  Jan                              6            7             8,                 9    
   feb                              3,              8 ,             7,           8

  I have these four above rows in my list and having a where condion for type = current and
 month

  I got a list now with four rows, is there any way i can write a LINQ query common to two grids
  to get the total row for both of them..


 

 
0
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35751006
So do you have something like this (data-wise, not necessarily structure-wise)?
List<Inventory> items = new List<Inventory>()
            {
                new Inventory() { Month = "Jan", Type = "Current", Pens = 3, Pencils = 4, Books = 5, Bags = 6 },
                new Inventory() { Month = "Feb", Type = "Current", Pens = 3, Pencils = 5, Books = 7, Bags = 8 }
                new Inventory() { Month = "Jan", Type = "Old", Pens = 6, Pencils = 7, Books = 8, Bags = 9 },
                new Inventory() { Month = "Feb", Type = "Old", Pens = 3, Pencils = 8, Books = 7, Bags = 8 }
            };

Open in new window

0
 

Author Comment

by:ram27
ID: 35751105
Yes i had something like that in my list which consists all the rows for two grids

I want to calculate the total of them and display...

like below..

   RowHeader              pens           pencils      books        bags
  Jan                               3             ,4              5 ,           6
    feb                              3,              5 ,             7,           8
 tota                              6              9                12          14
 
GRID 2:  
Moth Statistics

 RowHeader              pens           pencils      books        bags
  Jan                              6            7             8,                 9    
   feb                              3,              8 ,             7,           8

  totoal                         9               15          15           17


How can i calculate the total of them seperately and display in the grid
so that the code will be common for both
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35753735
For current, you could do something like this:

var current = items.Where(item => item.Type == "Current");

var totals = new
{
    Pens = current.Sum(item => item.Pens),
    Pencils = current.Sum(item => item.Pencils),
    Books = current.Sum(item => item.Books),
    Bags = current.Sum(item => item.Bags)
};

Open in new window


For monthly totals, if I'm interpreting your data correctly, you could use a "group by":

var results = from item in items
              group item by item.Month into g1
              select new
              {
                  Pens = items.Sum(item => item.Pens),
                  Pencils = items.Sum(item => item.Pencils),
                  Books = items.Sum(item => item.Books),
                  Bags = items.Sum(item => item.Bags)
              };

Open in new window

0
 

Author Comment

by:ram27
ID: 35755326
Hi, Thanks,

Is there any way i can totoal them in single line of code, because i have
12 grids like that..  
 I mean without specifying pens, pencils etc.. every time..
 I want to write a function common to do the total for all my grids..
 and in some Grids my properties will be different( mean gird headers). like

                    shoes         dress              socks
     wed          3             5                  6
     Thu          7              8                9
     totoal          10      13             15

 
 Thanks
0
 
LVL 3

Accepted Solution

by:
nixkuroi earned 2000 total points
ID: 36558587
Let's say you have an XML chunk with your values that looks like this:
string itemXML = "<items><item month=\"jan\" pens=\"3\" books=\"7\" bags=\"8\"/><item month=\"jan\" pens=\"3\" books=\"7\" bags=\"8\"/><item month=\"jan\" pens=\"3\" books=\"7\" bags=\"8\"/></items>";

The following code should let you create a completely dynamic dictionary of totals based on any number of attributes.  It'll dynamically add all of your attributes that have numeric values and leave them in the "totals" dictionary of <string, int>.

XElement xItems = XElement.Parse(itemXML);

Dictionary<string,int> totals = new Dictionary<string,int>();

foreach (XElement item in xItems.Elements("item").ToList())
{
    foreach (XAttribute att in item.Attributes())
    {
        int tmpVal = -1;
        bool isInt = Int32.TryParse(att.Value,out tmpVal);
        if (isInt)
        {
             if (!totals.ContainsKey(att.Name.LocalName))
                totals.Add(att.Name.LocalName,tmpVal);
             else
               totals[att.Name.LocalName]+=tmpVal;
        }

    }
}

How's that?
0
 
LVL 3

Expert Comment

by:nixkuroi
ID: 36558598
BTW:  This example requires the System.Xml.Linq namespace.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Loops Section Overview
Is your OST file inaccessible, Need to transfer OST file from one computer to another? Want to convert OST file to PST? If the answer to any of the above question is yes, then look no further. With the help of Stellar OST to PST Converter, you can e…
Suggested Courses
Course of the Month12 days, 2 hours left to enroll

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question