简体   繁体   中英

How can I return two fields using Linq on an object with more than two fields?

What I would like to do is something I find common in MySQL which is to select all of one field distinct, and a sum of another field in that data sub-set for each unique/distinct result.

Following should replicate something simple to use in order to see the type of data I mean :

public class Stock {
   public int id {get;set;}
   public int count {get;set;}
   public string location {get;set;}
   public Stock() { }
}

public class Foo {

   public void Bar() {
        List<Stock> Stocks = new List<Stock>()
        {
            new Stock
            {
                id = 137829,
                count = 5,
                location = "Ottawa"
            },
            new Stock
            {
                id = 137829,
                count = 27,
                location = "Toronto"
            },
            new Stock
            {
                id = 137830,
                count = 8,
                location = "Toronto"
            }

        };

        var result = Stocks.DistincyBy( s => s.id);
   }
}

What I would like to store in result is as follows (using this code as an example. the real project the structure is more complex).

  • id = 137829, count = 32
  • id = 137830, count = 8

I know I can use .Sum() , but in this scenario I wish to sum where one field is distinct. How can this be achieved (i prefer my Linq to be inline syntax rather than sql style querying)

Use GroupBy to get the distinct groupings, then Select into your objects. For example:

var result = Stocks.GroupBy(s => s.Id).Select(g => new 
{
   Id = g.Key,
   Count = g.Sum(i => i.Count)
};

Better would be to create a named class to select into, but the syntax would be very similar.

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