将值从另一个分配给CSV文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将值从另一个分配给CSV文件相关的知识,希望对你有一定的参考价值。

我有两个csv文件,其中包含10辆汽车和15位驾驶员的日历。目标是同时加入两个日历。

Car.csv看起来像这样

Car 1;A
Car 2;A
Car 3;I
Car 4;A
Car 5;A
Car 6;I
Car 7;A
Car 8;A
Car 9;Y
Car 10;A

Driver.csv看起来像这样

Driver 1;V
Driver 2;V
Driver 3;Y
Driver 4;A
Driver 5;A
Driver 6;V
Driver 7;A
Driver 8;I
Driver 9;I
Driver 10;V
Driver 11;V
Driver 12;A
Driver 13;A
Driver 14;A
Driver 15;A

所需的输出必须是

Car 1;Driver 4
Car 2;Driver 5
Car 3;Driver 8
Car 4;Driver 7
Car 5;Driver 12
Car 6;Driver 9
Car 7;Driver 13
Car 8;Driver 14
Car 9;Driver 3
Car 10;Driver 15

我的代码:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim car As String() = IO.File.ReadAllLines("path\car.csv").ToArray
        Dim drivers As String() = IO.File.ReadAllLines("path\driver.csv").ToArray
        Dim sb As New List(Of String)
        For Each line In car ' loop throw car
            Dim Fields1 = line.Split(";"c)
            For Each line1 In drivers 'loop throw driver
                Dim Fields2 = line1.Split(";"c)
                Dim driver As String = Fields2(0)
                If Fields1(1) = Fields2(1) Then
                    Fields1(1) = driver
                    sb.Add(String.Join(";", Fields1))
                End If
            Next
        Next
        IO.File.WriteAllLines("path\joined.csv", sb.ToArray())
    End Sub

不幸的是输出看起来不正确

Car 1;Driver 4
Car 2;Driver 4
Car 3;Driver 8
Car 4;Driver 4
Car 5;Driver 4
Car 6;Driver 8
Car 7;Driver 4
Car 8;Driver 4
Car 9;Driver 3
Car 10;Driver 4

如何避免分配已使用的值?我试图粘贴内部循环Fields2(1)="used",但是它不起作用。我在这里迷路了。

因为我对在vb.net中解析csv更加熟悉,所以我用它编写了代码,但是另外,对于31列的整个日历和Excel VBA,我都需要它,但这是另一回事了。

谢谢您的回答!

答案
这应该使您非常接近。

Private Sub MatchCarsButton_Click(sender As Object, e As EventArgs) Handles MatchCarsButton.Click Try Dim cars As List(Of String) = File.ReadAllLines("cars.csv").ToList Dim drivers As List(Of String) = File.ReadAllLines("drivers.csv").ToList Dim result As List(Of String) = MatchVehicles(cars, drivers) File.WriteAllLines("out.csv", result) Catch ex As Exception MessageBox.Show(String.Concat("An error occurred :", ex.Message)) End Try End Sub Private Function MatchVehicles(cars As List(Of String), drivers As List(Of String)) As List(Of String) Dim result As New List(Of String) For Each car As String In cars Dim carVals() As String = car.Split(";"c) For Each driver As String In drivers Dim driverVals() As String = driver.Split(";"c) If carVals(1) = driverVals(1) Then result.Add(String.Format("{0};{1}", carVals(0), driverVals(0))) drivers.Remove(driver) ' remove them from the list Exit For ' exit the loop End If Next Next Return result End Function

以上是关于将值从另一个分配给CSV文件的主要内容,如果未能解决你的问题,请参考以下文章

如何将值从片段/活动传递到 xml?

将值从向量分配给动态数组(C++)

如何将值从其他活动传递给 viewpager 片段?

Objective-c:将值从 AppDelegate 传递给 UIViewController

将值从数据库传递到 vue 组件并将其分配给变量

将值从闭包赋值给变量 Swift