c# 解析txt 统计
问题描述:
abc表示该行描述的是一个产品,10/11代表产品编号,2表示产品数量
aa表示该行是对产品的描述信息(产品良好或不良),10/11来自abc编号,1表示产品数量
产品实体类product,有如下字段:
id,name,count(数量),remarks,goodproductNo(良品数量),badproductNo(次品数量)
问题是:如何用程序来分别统计编号为10,11的产品到底有多少良品,多少不良品,然后赋
值给实体类product,
* aaa.txt *
abc|10|测a试1|2|备注|
abc|11|测a试2|3|备注|
aa|10|1|良好商品·|
aa|10|1|良好商品·|
aa|11|1|不良商品·|
aa|11|1|良好商品·|
aa|11|1|良好商品·|
代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string[] temp = System.IO.File.ReadAllLines("E:\\aaa.txt", System.Text.Encoding.GetEncoding("gb2312")); Dictionary<int, product> dic = new Dictionary<int, product>(); foreach (string s in temp) { if (s.StartsWith("abc")) { string[] pInfo = s.Split('|'); int id = int.Parse(pInfo[1]); if (!dic.ContainsKey(id)) { product p = new product(); p.Id = id; p.Name = pInfo[2]; p.Count = int.Parse(pInfo[3]); p.Remarks = pInfo[4]; dic.Add(id, p); } } else if (s.StartsWith("aa")) { string[] qInfo = s.Split('|'); int id = int.Parse(qInfo[1]); if (dic.ContainsKey(id)) { product p = dic[id]; int count = int.Parse(qInfo[2]); string quality = qInfo[3]; if (quality == "良好商品·") p.GoodProductNo += count; else if (quality == "不良商品·") p.BadProductNo += count; } } } foreach (int i in dic.Keys) { product p = dic[i]; Console.WriteLine("Id:{0},name:{1},count:{2},remarks:{3},goodproductNo:{4},badproductNo:{5}", p.Id, p.Name, p.Count, p.Remarks, p.GoodProductNo, p.BadProductNo); } Console.ReadKey(); //任意键退出 } } }
/*
输出:
Id:10,name:测试1,count:2,remarks:备注,goodproductNo:2,badproductNo:0
Id:11,name:测试2,count:3,remarks:备注,goodproductNo:2,badproductNo:1
*/
实体类product.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class product { private int _id = 0; private int _count = 0; private int _goodproductNo = 0; private int _badproductNo = 0; private string _name = null; private string _remarks = null; public int Id { get { return this._id; } set { this._id = value; } } public int Count { get { return this._count; } set { this._count = value; } } public int GoodProductNo { get { return this._goodproductNo; } set { this._goodproductNo = value; } } public int BadProductNo { get { return this._badproductNo; } set { this._badproductNo = value; } } public string Name { get { return this._name; } set { this._name = value; } } public string Remarks { get { return this._remarks; } set { this._remarks = value; } } } }