根据第一数组结果从第二数组中选择字符串

时间:2018-09-30 20:26:05

标签: c#

我正在根据第一个数组中的结果从第二个数组中进行选择。第一个数组存储驻留在csv中的某些列标题的位置的整数。

var path = @"C:\Temp\file.csv";
using (TextFieldParser csvImport = new TextFieldParser(path))
{
    csvImport.CommentTokens = new string[] { "#" };
    csvImport.SetDelimiters(new string[] { "," });
    csvImport.HasFieldsEnclosedInQuotes = true;

    string[] header = csvImport.ReadFields();
    foreach (string colheader in header)
    {
        index = index + 1; //this bit will return where my column headers are in the header line
        if (colheader == "FirstColumn")
        {
            key = (index - 1); //stores int of my result
        }
        else if (colheader == "SecondColumn")
        {
            secondkey = (index - 1); //stores int of my result
        }
    }

    csvImport.ReadLine();   //Behaves as carriage line return, this moves to position 2 before loop

    while (!csvImport.EndOfData)
    {
        //Read each field, build Sql Statement
        string[] fields = csvImport.ReadFields();
        string MyKey = fields[1];   //Currently this is static pos 1 I want it to be the result of key 
        string MySecondKey = fields[74]; //Currently this is static pos 74 I want it to be the result of SecondKey 
    }
}

是否有一种简单的方法将变量分配给[]以根据我可以使用的其他变量临时挑选我的数组?

我已经略微编辑了问题,因为我要实现的目标是根据第一个arra的索引从csv行中选择字段

            //Read each field, build Sql Statement
        string[] fields = csvImport.ReadFields();
        string MyKey = fields[1];   //Currently this is static pos 1 I want it to be the result of key 
        string MySecondKey = fields[74]; //Currently this is static pos 74 I want it to be the result of SecondKey 

1 个答案:

答案 0 :(得分:0)

为第二个数组中的项目提供索引(此处为i),然后获取其索引位于第一个数组中的所有项目:

secondArray.Select((x,i) => new {x, i})
         .Where(z => firstArray.Contains(z.i))
         .Select(z => z.x);

这是live demo

(当然,第二个数组的类型并不重要,我只是为了简单起见使用string[],它可以是类的数组,...)