c#中比较两列字符串的最快方法

本文关键字:字符串 方法 两列 比较 | 更新日期: 2023-09-27 18:04:37

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

是否有任何快速的方法来做同样的事情,而且因为在两列中可以很大,所以需要有效的方法来做。

我需要从一些表中获取两个列值。那么,数组是保存这些值的好方法呢,还是其他需要使用的结构体呢?

谢谢,

c#中比较两列字符串的最快方法

通过Except LINQ扩展方法,

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

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

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

如果速度是你所关心的,你可以使用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();

更合适

试试这个:

 List<string> resultList =  SecondList.Except(FirstList).ToList();
var arr1 = new string [] { "b1", "b3"};
var arr2 = new string [] { "b1", "b2"};
arr1.SequenceEqual(arr2);