查找CSV文件中每一列的最大长度 [英] Find the maximum length of every column in a csv file

查看:316
本文介绍了查找CSV文件中每一列的最大长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图在控制台应用程序中显示一个csv文档.但是,由于其中文本大小的变化,输出不是可显示的格式.

So, I was trying to present a csv document in a console application. However, due to the varying text size in it, the output was not in a presentable format.

为了展示它,我尝试计算每一列的最大文本长度,然后在该列中的其余文本后面加上空格,以使每一列中的字符长度相等.

To present it, I tried to count the maximum length of text for each column and then append white space to the remaining text in that column so that there's equal length of characters in each column.

我试图获取字符数,但似乎无法弄清楚如何进行进一步的操作.

I tried to get the character count, but can't seem to figure out how to proceed further.

var file = File.ReadAllLines(@"E:\File.csv");
var lineList = file.Select(x => x.Split(',').ToList()).ToList();
int maxColumn = lineList.Select(x => x.Count).Max(x => x);
List<int> maxElementSize = new List<int>();
for (int i = 0; i < maxColumn; i++)
{
    //Some Logic    
}

任何帮助将不胜感激.

推荐答案

尝试使用嵌套的for循环:

Try with a nested for loop:

var inputLines = File.ReadAllLines(@"E:\File.csv");   
Dictionary<int,int> dictIndexLenght = new Dictionary<int,int>();
foreach(var line in inputLines)
{
    List<string> columList =  line.Split(',').ToList();
    for (int i = 0; i < columList.Count; i++)
    {
        int tempVal = 0;
        if(dictIndexLenght.TryGetValue(i,out tempVal))
        {
            if(tempVal<columList[i].Length)
            {
                dictIndexLenght[i]=columList[i].Length;
            }                  
        }
        else
            dictIndexLenght[i]=columList[i].Length;
    }

}

可以在此处或使用以下代码行检查结果:

Can check the result here or with this lines of code:

for(int i=0;i<dictIndexLenght.Count;i++)
{
    Console.WriteLine("Column {0} : {1}", i, dictIndexLenght[i]);
}   

这篇关于查找CSV文件中每一列的最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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