使用 Linq 中的 Contains 在大列表中查找

Find within large list using Contains within Linq

我有两个大 excel 文件。我能够使用 linqtoexcel 将这些 excel 文件的行放入列表中。问题是我需要使用第一个列表中一个对象的字符串来 查找它是否属于或包含在第二个列表的对象中的另一个字符串 中。我正在尝试以下操作,但由于每个列表都超过 70,000 个项目,所以这个过程需要很长时间。

我试过使用 Any 语句,但无法提取结果。如果您有任何想法,请分享。

List<ExcelOne> exOne = new List<ExcelOne>();
List<ExcelTwo> exTwo = new List<ExcelTwo>();

我能够构建第一个列表和第二个列表,并且可以验证列表中是否存在对象。这是我对如何通过列表查找匹配项的想法。请注意,一旦找到匹配,我想创建一个新的 class 并将其添加到新列表中。

 List<NewFormRow> rows = new List<NewFormRow>();

        foreach (var item in exOne)
        {
             //I am going through each item in list one
            foreach (var thing in exTwo)
            {
                  //I now want to check if exTwo.importantRow has or 
                  //contains any part of the string from item.id
                if (thing.importantRow.Contains(item.id))
                {
                    NewFormRow adding = new NewFormRow()
                    {
                        Idfound = item.id,
                        ImportantRow = thing.importantRow
                    };
                    rows.Add(adding);
                    Console.WriteLine("added one");
                }
            }

如果您知道更快的解决方法,请分享。谢谢你。

很难改进这种子字符串方法。问题是你是否必须在这里做。你不能在你填满清单的地方做吗?那么您就不需要这个额外的步骤了。

但是,您可能会发现此 LINQ 查询更具可读性:

List<NewFormRow> rows = exOne
    .SelectMany(x => exTwo
        .Where(x2 => x2.importantRow.Contains(x.id))
        .Select(x2 => new NewFormRow
        {
            Idfound = x.id,
            ImportantRow = x2.importantRow
        }))
    .ToList();