日期:2014-05-20  浏览次数:20812 次

文本数据处理
求教 , 我想处理一个如下格式的文本文件:

a00001,2
a00001,-1
b00001,1
b00001,1

获得如下结果:

a00001,1
b00001,2

即: 最后一个逗号位后面的数字代表数量 , 前面一个字串代表物品 , 按行存储, 我想将同一个物品根据数量汇总在一行...

这个如何实现呢...

------解决方案--------------------
C# code
s = @"a00001,2
a00001,-1
b00001,1
b00001,1
";
var query = from x in s.Split(new char[] { '\r', '\n' })
                       .Select(x => new { id = x.split(',')[0], value = Convert.ToInt32(x.split(',')[1]) })
           group x by x.id into g
           select new { id = g.Key, value = g.Select(x => x.value).Sum() };
foreach (var item in query)
{
    Console.WriteLine(item.id + "," + item.value);
}

------解决方案--------------------
C# code

        public static List<String[]> ReadTxt(string filePathName)
        {
            List<String[]> ls = new List<String[]>();
            StreamReader fileReader=new   StreamReader(filePathName); 
            string strLine="";
            while (strLine != null)
            {
                strLine = fileReader.ReadLine();
                if (strLine != null && strLine.Length>0)
                {
                    ls.Add(strLine.Split(','));
                    //Debug.WriteLine(strLine);
                }
            }
            fileReader.Close();
            return ls;
        }

------解决方案--------------------
string s = @"a00001,2
a00001,-1
b00001,1
b00001,1";
var query = from x in s.Split(new string[] { "\r\n" }, StringSplitOptions.None)
.Select(x => new { id = x.Split(',')[0].Trim(), value = Convert.ToInt32(x.Split(',')[1]) })
group x by x.id into g
select new { id = g.Key, value = g.Select(x => x.value).Sum() }; 
foreach (var item in query) 

Console.WriteLine(item.id + "," + item.value); 
}
------解决方案--------------------
探讨
引用:

s = @"a00001,2
a00001,-1
b00001,1
b00001,1
";
var query = from x in s.Split(new char[] { '\r', '\n' })
.Select(x => new { id = x.split(',')[0], value = Convert.ToI……