【问题标题】:fastest way to compare two columns of strings in C#在 C# 中比较两列字符串的最快方法
【发布时间】:2014-05-22 05:28:09
【问题描述】:

我正在尝试使用 equal 方法比较两列类型字符串。将两列存储在两个不同的数组中。

是否有任何快速的方法可以做到这一点,而且由于两列可能很大,所以需要有效的方法来做到这一点。

我需要从某个表中获取两列值。所以数组是保存值或其他需要使用的结构的好主意。

谢谢,

【问题讨论】:

  • 如果列中没有可重复的值,您可以将这些值保存在 HashSet<String>;如果有可重复的值 - Dictionary。在您的问题中,基于哈希的集合比数组/列表更有效
  • @Dmitry Bychenko - 两列中的值都有可重复的值。
  • 你有数据库,不能在查询中做比较吗?

标签: c# performance string-comparison


【解决方案1】:

通过使用ExceptLINQ扩展方法,

List<string> resultList =  SecondList.Except(FirstList).ToList();

【讨论】:

  • 这是最快的方式.. 即使列表的大小增长到大约 1000 或更多?
  • 1000 不算大。你想检查它们是否不同吗?如果是这样,请使用 IEnumerable + count 来节省一些迭代 - 但我认为这不会产生很大的影响,因为 1000 个值实际上什么都不是......
【解决方案2】:

您可以使用Except 函数来比较两个列表。像这样的:

List<string> result = list1.Except(list2).ToList();

【讨论】:

    【解决方案3】:

    如果您只关心速度,您可以在获取数据时使用Dictionary 而不是Lists/Arrays

    // Key (string) - String value
    // Value (int)  - repeat count
    Dictionary<String, int> values = new Dictionary<String, int>();
    
    // Fill values: adding up v1, removing v2
    using (IDataReader reader = myQuery.ExecuteReader()) {
      while (reader.Read()) {
        //TODO: put here the right reader index
        String v1 = reader[1].ReadString();
        String v2 = reader[2].ReadString(); 
    
        int repeatCount;
    
        if (values.TryGetValue(v1, out repeatCount)) 
          values[v1] = repeatCount + 1;
        else 
          values[v1] = 1;
    
        if (values.TryGetValue(v2, out repeatCount))
          values[v2] = repeatCount - 1;
        else 
          values[v2] = -1;
      }
    }
    
    // Select out the keys with positive values (where repeat count > 0)
    List<String> result = values
      .Where(pair => pair.Value > 0)
      .Select(pair => pair.Key)
      .ToList();
    

    但是,Linq 解决方案

      List<String> result = List1.Except(List2).ToList();
    

    体型更大

    【讨论】:

      【解决方案4】:

      试试这个:

       List<string> resultList =  SecondList.Except(FirstList).ToList();
      

      【讨论】:

        【解决方案5】:
        var arr1 = new string [] { "b1", "b3"};
        var arr2 = new string [] { "b1", "b2"};
        
        arr1.SequenceEqual(arr2);
        

        【讨论】:

          猜你喜欢
          • 2019-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-04
          • 1970-01-01
          • 2018-03-14
          相关资源
          最近更新 更多