c#用于存储来自csv文件的值的适当数据结构.具体案例

Tir*_*ing 7 c# csv data-structures

我正在编写一个程序,它只会读取包含以下信息的2个不同的.csv文件:

file 1                  file2
AA,2.34                BA,6.45
AB,1.46                BB,5.45
AC,9.69                BC,6.21
AD,3.6                 AC,7.56
Run Code Online (Sandbox Code Playgroud)

第一列是string第二列,第二列是double.

到目前为止,我没有困难阅读这些文件并将值放入List:

firstFile = new List<KeyValuePair<string, double>>();
secondFile = new List<KeyValuePair<string, double>>();
Run Code Online (Sandbox Code Playgroud)

我正在尝试指导我的程序:

  • 从第一个文件的第一行的第一列获取第一个值(在这种情况下AA)
  • 并查看第二个文件中的整个第一列中是否存在匹配项.
  • 如果找到字符串匹配,则比较它们对应的第二个值(double在这种情况下),如果在这种情况下匹配,则将整行添加到单独的行中List.

类似于下面的伪代码:

for(var i=0;i<firstFile.Count;i++)
{
    firstFile.Column[0].value[i].SearchMatchesInAnotherFile(secondFile.Column[0].values.All);
    if(MatchFound)
    {
        CompareCorrespondingDoubles();
        if(true)
        {
            AddFirstValueToList();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是List我尝试使用,Dictionary但这个数据结构没有排序,也无法通过索引访问密钥.

不是要求提供确切的代码,而是问题是:

你建议将什么作为该程序的适当数据结构使用,以便我可以进一步调查自己?

Ren*_*ogt 8

KeyValuePair实际上只用于Dictionarys.我建议你创建自己的自定义类型:

public class MyRow
{
    public string StringValue {get;set;}
    public double DoubleValue {get;set;}

    public override bool Equals(object o)
    {
         MyRow r = o as MyRow;
         if (ReferenceEquals(r, null)) return false;
         return r.StringValue == this.StringValue && r.DoubleValue == this.DoubleValue;
    }
    public override int GetHashCode()
    {
        unchecked { return StringValue.GetHashCode ^ r.DoubleValue.GetHashCode(); }
    }
}
Run Code Online (Sandbox Code Playgroud)

并将文件存储在此类型的列表中:

List<MyRow> firstFile = ...
List<MyRow> secondFile = ...
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过LINQ的方法确定交集(两个列表中出现的所有元素)Intersect:

var result = firstFile.Intersect(secondFile).ToList();
Run Code Online (Sandbox Code Playgroud)

这是必要的覆盖EqualsGetHashCode,否则Intersect只会使一个参考比较.另外,你可以实现一个自己IEqualityComparer<MyRow, MyRow>进行比较并将其传递给适当的Intersect重载.


但是如果你能确保键(字符串值是唯一的),你也可以使用

Dictionary<string, double> firstFile = ...    
Dictionary<string, double> secondFile = ...
Run Code Online (Sandbox Code Playgroud)

在这种情况下使用此LINQ语句:

var result = new Dictionary<string, double>(
          firstFile.Select(x => new { First = x, Second = secondFile.FirstOrDefault(y => x.Key == y.Key) })
                   .Where(x => x.Second?.Value == x.First.Value));
Run Code Online (Sandbox Code Playgroud)

时间复杂度为O(m + n),而上部解决方案为O(m*n)(m和n为两个文件的行数).