当sum中的表达式是字符串时,如何在linq中进行分组和求和?

时间:2018-05-13 18:19:04

标签: c# linq sum

从SOAP api(wsdl)我得到了包含Ids和数量结果的列表,如下所示:

[0] Id: "000123-12B024", Qty: "20"
[1] Id: "000123-12B025", Qty: "30"

...等 返回的结果都是字符串,Id和Qty。

现在我想要解析前六个标志(签署" - ")和组ID和总和数量。因此,例子的结果将是:

[0] Id:" 000123",数量:" 50" 等

我的代码是:

var res = _listOfProductIdAndStock.Where(ids => ids.product_sku.Contains(@"-"))
                .Select(ids => new { id = ids.product_sku.Split(Convert.ToChar("-"))[0], ids.qty })
                /*To here code is fine, so my results is like:
                 * [0] Id: "000123", Qty: "20"
                 * [1] Id: "000123", Qty: "30"
                 * Next I whant to group it by "Id" and sum "qty" field which is string
                 */                      
                .GroupBy(ids => ids.id)
                .Select(ids => new {ids.FirstOrDefault().id, ids.Sum(a => a.qty)})
                // Here I get error in ids.Sum that I cannot convert expression type string to return type ('decimal,int,float etc.)
                .ToList();

我不知道如何转换它,或者很可能

0 个答案:

没有答案