简体   繁体   English

如何在具有两个以上字段的对象上使用Linq返回两个字段?

[英]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. 我想做的是在MySQL中发现的一个共同点,那就是为每个唯一/不同的结果选择一个不同的字段,并在该数据子集中选择另一个字段的总和。

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). 我想要存储的result如下(以该代码为例。实际项目的结构更加复杂)。

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

I know I can use .Sum() , but in this scenario I wish to sum where one field is distinct. 我知道我可以使用.Sum() ,但是在这种情况下,我希望总结一个字段是不同的地方。 How can this be achieved (i prefer my Linq to be inline syntax rather than sql style querying) 如何做到这一点(我更喜欢Linq是内联语法而不是sql样式查询)

Use GroupBy to get the distinct groupings, then Select into your objects. 使用GroupBy获取不同的分组,然后Select进入对象。 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. 最好创建一个命名类供选择,但是语法非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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