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

问题描述 投票:0回答:5

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

有没有快速的方法可以做到同样的事情,而且由于两列可能很大,所以需要有效的方法来做到这一点。

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

c# performance string-comparison
5个回答
3
投票

通过使用

Except
LINQ 扩展方法,

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

2
投票

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

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

1
投票

如果您只关心速度,则在获取数据时可以使用

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();

更简洁


1
投票

试试这个:

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

1
投票
var arr1 = new string [] { "b1", "b3"};
var arr2 = new string [] { "b1", "b2"};

arr1.SequenceEqual(arr2);
© www.soinside.com 2019 - 2024. All rights reserved.