C#Groupby,然后在分割CSV之后求和(无标题) [英] C# Groupby then Sum after Split CSV (no Headers)
问题描述
阅读过各种文章之后,我认为我已经接近想要的结果了,但是求和"部分给出了错误的答案.我怀疑是由于我的csv文件没有列标题而导致的,因为我称之为"sum".
Having read the various post, I think I'm close to getting the result I want but the "sum" part is giving the wrong answer. I suspect its due to the way I call the "sum" as my csv file does not have column headers.
csv文件包含以下内容:
csv file contains the following:
222,1
222, 1
223,2
222,1
224,2
222,-1
我想要做的是
- 读取CSV文件并拆分数据
- 按第一列分组
- 按组汇总第二列
这是我到目前为止所做的:
Here is what I have done so far:
var newquery = from line in File.ReadAllLines(path_source) //read all lines in csv file
let values = line.Split(',') //split the values by separator
let price_value = values[0]
group line by price_value into g
orderby g.Key
//select g;
select new
{
price_column = g.Key,
qty_column = g.Sum(x => x[1])
};
var writesum = newquery.Select(record => record.price_column + "," + record.qty_column);
File.WriteAllLines(path_target, writesum);
path_target文件显示:
The path_target file shows:
222,45
222, 45
223,80
224、65
这告诉我split
,groupby
,orderby
语法正确,但是sum
完全错误.
This tells me that the split
, groupby
, orderby
syntax is correct but the sum
is totally wrong.
我怀疑sum
结果错误的原因之一是由于qty_column = g.Sum(x => x[1])
的语法.
I suspect one of the reasons the results for the sum
is wrong is due to the syntax here qty_column = g.Sum(x => x[1])
.
由于我的数据不包含标头,因此无法像示例中那样调用x.something
.
As my data does not contain headers, I'm not able to call x.something
as in the examples.
另一方面,在这一点上我可能是完全错误的!
On the other hand I could be totally wrong on this point!
非常感谢您的帮助.
推荐答案
首先,将值拆分后进行分组,而不是原始行:
First of all, group the values after they are splitted, not the raw line:
group values by price_value into g
代替
group line by price_value into g
在对它们求和之前,下一步将要求和的string
解析为ints
:
Next parse the string
you want to sum as ints
before you sum them:
qty_column = g.Sum(x => int.Parse(x[1]))
代替
qty_column = g.Sum(x => x[1])
因为x[1]
是string
.
现在的结果是:
var newquery = from line in File.ReadAllLines(path_source) //read all lines in csv file.
let values = line.Split(',') //split the values by separator
let price_value = values[0]
group values by price_value into g
orderby g.Key
//select g;
select new
{
price_column = g.Key,
qty_column = g.Sum(x => int.Parse(x[1]))
};
哪个给您:
222,1
222, 1
223,2
224,2
无论如何,流利的语法将更具可读性:
Anyway, fluent syntax will be somewhat more readable:
var v = new List<string> File.ReadAllLines(path_source) //read all lines in csv file.
.Select(x => x.Split(','))
.Select(x => new { Key = x.First(), Value = x.Last() })
.GroupBy(x => x.Key)
.Select(x => new
{
price_column = x.Key,
qty_column = x.Sum(y => int.Parse(y.Value))
});
这篇关于C#Groupby,然后在分割CSV之后求和(无标题)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!