简体   繁体   English

string。加入Linq查询以合并数组中的两个字符串并输出为单个逗号分隔的字符串

[英]string.Join Linq query to merge two strings from an array and output as single comma delimited string

As part of a data cleansing exercise I need to correct the formatting of a csv file. 作为数据清理工作的一部分,我需要更正csv文件的格式。

Due to poor formatting/lack of quotes an extra comma in a description field is breaking my DTS package. 由于格式不佳/引号不足,描述字段中的一个逗号引起了我的DTS软件包的损坏。

So, to get around this I have created a simple C# script to find any line in the csv that contains more columns than the header row. 因此,为了解决这个问题,我创建了一个简单的C#脚本来查找csv中包含比标题行更多列的任何行。

When the row contains more columns than the header I want to merge array item [10] and [11] into one column and then write the line to my new file - keeping all the other existing columns as they are. 当行包含的列多于标题时,我想将数组项[10]和[11]合并为一列,然后将该行写入我的新文件-保留所有其他现有列。

Code: 码:

    var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();

    if (headers == null) headers = new string[columns.Length];

    if (columns.Length != headers.Length)
    {
        // TODO - Linq to write comma separated string but merge column 10 and 11 of the array
        // writer.WriteLine(string.Join(delimiter, columns));
    }
    else
    {
        writer.WriteLine(string.Join(delimiter, columns));
    }

Unfortunately, my Linq writing skills are somewhat lacking, can someone please help me fill in the TODO. 不幸的是,我的Linq写作技能有些欠缺,有人可以帮我填写TODO。

Simply use for columns list instead of array. 只需用于列列表而不是数组即可。 That will allow you to remove unnecessary columns after merge: 这样,您可以在合并后删除不必要的列:

var columns = splitExpression.Split(line).Where(s => s != delimiter).ToList();

if (headers == null) headers = new string[columns.Count];

if (columns.Count != headers.Length)
{
    columns[10] = columns[10] + columns[11]; // combine columns here
    columns.RemoveAt(11);       
}

writer.WriteLine(string.Join(delimiter, columns));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM