我正在尝试使用 equal 方法比较两个类型字符串列表。将两列存储在两个不同的数组中。
是否有任何快速方法可以执行相同的操作,而且由于两个列表中的条目数量可能很大,所以我需要有效的方法来执行此操作。
我需要从某个表中获取两个列表值。数组是保存值的好主意还是需要使用其他一些结构?
您可以使用 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);