基于另一个列表上的名单中提取的快速方法 [英] Fast way of extraction of a list based on another list

查看:119
本文介绍了基于另一个列表上的名单中提取的快速方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List1: {"123456", "432978", "321675", …}  // containing 100,000 members

List2: {"7674543897", "1234568897", "8899776644",…} // containing 500,000 members

我想提取中的所有项目list2中,他们的前6位来自List1中成员,因此这里的字符串,因为它的前6位来自List1中的第一项1234568897是有效的。
它所这个干什么?

I want to extract all items in List2 that their first 6 digits are from List1 members, so here the string "1234568897" is valid because its first 6 digits are from List1’s first item. What it the fastest way of doing this?

    foreach(string id in List1)
    {
    string result = List2.FirstOrDefault(x => x.Contains(id));
    if(result!=null)
      {
      //some works here
      }
}

这适用于一组小于1000,但是当列表2项增长这个时间太长

this works for a group of less than 1000 but when List2 items grows this takes too long

推荐答案

您可以使用 Enumerable.Join 是的非常有效

var match = from str1 in List1
            join str2 in List2
            on str1 equals (str2.Length < 6 ? str2 : str2.Substring(0, 6))
            select str2;

演示

修改

由于@Oleksandr Pshenychnyy认为,这将是与这样的大集合很慢,这里是List1中100000随机字符串和500000字符串列表2与同一范围内的问题的演示。它执行在600毫秒ideone:

Since @Oleksandr Pshenychnyy assumed that it would be very slow with such big collections, here is a demo with 100000 random strings in list1 and 500000 strings in list2 with the same range as in the question. It executes in 600 milliseconds on ideone:

的http:// ideone。 COM / rB6LU4

这篇关于基于另一个列表上的名单中提取的快速方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆