2

From SOAP api (wsdl) I am getting list with results of Ids and quantity like this:

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

Etc... Where both returned results are string, Id and Qty.

Now I whant to Id parse into first six signs (to sign "-") and group Id and sum qty. So result from example would be:

[0] Id: "000123", Qty: "50" Etc

My code is:

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();

I don't know how to convert it, or cast it probably

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
DaniKR
  • 2,418
  • 10
  • 39
  • 48
  • This link should be helpful - https://stackoverflow.com/questions/20375437/convert-string-to-int-for-sum-in-linq – Arpit Gupta May 13 '18 at 18:38

1 Answers1

1

Firstly, you can pass the character you want to split by directly to the Split method i.e.
Split('-') and avoid Split(Convert.ToChar("-")) completely.

var res = _listOfProductIdAndStock.Where(ids => ids.product_sku.Contains(@"-"))
                .Select(ids => new { id = ids.product_sku.Split('-')[0], ids.qty })
                .GroupBy(ids => ids.id)
                .Select(ids => new { ids.Key, 
                                 summation = ids.Sum(a => int.Parse(a.qty))})
                .ToList();

Then you can further simplify ids.FirstOrDefault().id to ids.Key; As for parsing the string, simply do ids.Sum(a => int.Parse(a.qty)).

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • Great this works, but only in decimals. I would prefer into "int" but when I run code I get an error that "Input string was not in a correct format." – DaniKR May 13 '18 at 18:41
  • @DaniKR if `Qty` can be a floating point number then change `int.Parse(a.qty)` to `decimal.Parse(a.qty)`, if it's only integers then make sure you trim off any illegal characters from the string before parsing. – Ousmane D. May 13 '18 at 18:43
  • @Anomine Yes thank you, my string were exactly like "0.0000" than I split also this part (with '.') and then i could use int – DaniKR May 13 '18 at 18:58