【问题标题】:Fastest way to cross check 2 Lists with eachother相互交叉检查 2 个列表的最快方法
【发布时间】:2017-12-19 12:22:44
【问题描述】:

检查 list1 中的字符串值是否存在于 list2 中的最有效方法是什么?

伪代码示例

StringList List1 = {"a", "b", "c", "d"};
StringList List2 = {"d", "c", "b", "a"};

foreach (string a in List1)
{
    foreach (string b in List2)
    {
        if(a==b)
        {
             WriteLine("match");
        }
    }
} 

这种方法太慢了,不是最好的解决方案,我正在使用的平台是 BI#,它是 C# 的衍生产品。当前库中不存在 Array.Exists。

【问题讨论】:

  • 先排序或制作查找表通常可以让您获得比二次算法更快的速度

标签: c# arrays list arraylist


【解决方案1】:

你可以使用Intersect:

var allIntersections = List1.Intersect(List2);

foreach(string match in allIntersections)
   Console.WriteLine(match);

如果您只想知道是否至少有一个相交:

bool anyExist = allIntersections.Any(); 

【讨论】:

  • 虽然这个库中不存在“相交”,但你给了我一个非常有效的想法,我会发布一个答案告诉我你的想法
  • @ArraysRus: 你必须将using System.Linq; 添加到你的类文件的顶部
  • @ArraysRus:你有HashSet<T>吗?
  • 我不能添加任何库,它不是标准 C# 平台,不,我没有 HashSet<T>
  • 这将是标准 C# 平台的正确答案,感谢您的帮助
【解决方案2】:

将列表转换为逗号分隔的字符串,允许使用标准的InString 函数,在这种情况下称为StringContains 的函数;

 foreach (string a in List1)
{
    if(StringContains(a, NewString))
    {
        WriteLine("Match");
    }
} 

【讨论】:

  • 有趣的是,这比使用双循环快多少。另外,明智地选择你的分隔符:)
【解决方案3】:
bool flag= list2.Except(list1).Any();

如果 list1 不包含 list2 中的所有内容,则为 true。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多