阅读使用LINQ的CSV [英] Read Csv using LINQ

查看:149
本文介绍了阅读使用LINQ的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个CSV文件

  A,22,23,12
B,32,4,33
C,34,3,33

我想打印每行的总和,平均跳过第一列。如何使用lambda在LINQ做


解决方案

  VAR的东西=由升的File.ReadAllLines(文件名)
            令x = l.Split(新[] {','','},StringSplitOptions.RemoveEmptyEntries)
                     .Skip(1)
                     。选择(S => int.Parse(S))
            新选择
            {
                总和= x.Sum()
                平均= x.Average()
            };

如果你正在读大文件和内存使用是一个问题,那么下面的工作更好地使用.NET 4:

  VAR的东西=由升的File.ReadLines(文件名)
            令x = l.Split(新[] {','','},StringSplitOptions.RemoveEmptyEntries)
                     .Skip(1)
                     。选择(S => int.Parse(S))
            新选择
            {
                总和= x.Sum()
                平均= x.Average()
            };

在这两种情况下,的东西变量包含枚举它实际上不会,直到你开始从中读取(例如在执行的foreach 循环)。

I am having a csv file like this

A, 22, 23, 12
B, 32, 4, 33
C, 34, 3 ,33

I want to print the sum and average of each row and skip the first column. How to do in LINQ using Lambda

解决方案

var stuff = from l in File.ReadAllLines(filename)
            let x = l.Split(new [] {',', ' '}, StringSplitOptions.RemoveEmptyEntries)
                     .Skip(1)
                     .Select(s => int.Parse(s))
            select new
            {
                Sum = x.Sum(),
                Average = x.Average()
            };

If you're reading big files and memory use is a concern, then the following will work better using .NET 4:

var stuff = from l in File.ReadLines(filename)
            let x = l.Split(new [] {',', ' '}, StringSplitOptions.RemoveEmptyEntries)
                     .Skip(1)
                     .Select(s => int.Parse(s))
            select new
            {
                Sum = x.Sum(),
                Average = x.Average()
            };

In both cases, the stuff variable contains an enumerable which won't actually be executed until you start reading from it (e.g. inside a foreach loop).

这篇关于阅读使用LINQ的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆