【问题标题】:Compare two Lists using Linq for partial matches使用 Linq 比较两个列表以进行部分匹配
【发布时间】:2015-12-19 01:03:14
【问题描述】:

我尝试查看其他一些问题,但找不到任何部分匹配的问题。

我有两个List<string>

他们有代码。一个是所选代码的列表,一个是所需代码的列表。整个代码列表虽然是一棵树,但它们有子代码。一个例子是 代码 B 代码 B.1 代码 B.11

假设要求的代码是 B,但它的树下的任何东西都将满足该要求,所以如果选择的代码是 A 和 C,匹配将失败,但如果选择的代码之一是 B.1,它包含部分匹配。

我只需要知道是否有任何选定的代码部分匹配任何必需的代码。这是我目前的尝试。

//Required is List<string> and Selected is a List<string>
int count = (from c in Selected where c.Contains(Required.Any()) select c).Count();

我得到的错误是在 Required.Any() 上,它不能从 bool 转换为 string。

抱歉,如果这令人困惑,如果添加任何其他信息会有所帮助,请告诉我。

【问题讨论】:

    标签: c# linq contains


    【解决方案1】:

    我认为你需要这样的东西:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    static class Program {
        static void Main(string[] args) {
            List<string> selected = new List<string> { "A", "B", "B.1", "B.11", "C" };
            List<string> required = new List<string> { "B", "C" };
            var matching = from s in selected where required.Any(r => s.StartsWith(r)) select s;
            foreach (string m in matching) {
                Console.WriteLine(m);
            }
        }
    }
    

    以这种方式在required 上应用Any 条件应该会为您提供匹配的元素 - 我不确定您应该使用StartsWith 还是Contains,这取决于您的要求。

    【讨论】:

    • 效果很好,感谢您的帮助。今天我在这个问题上呆了这么久,我的大脑变成了糊状,我一直盯着这个东西想弄清楚。
    【解决方案2】:

    如果选择的和所需的列表足够大,则以下比接受的答案更快:

    static void Main(string[] args)
    {
        List<string> selected = new List<string> { "A", "B", "B.1", "B.11", "C" };
        List<string> required = new List<string> { "B", "C" };
        required.Sort();
        var matching = selected.Where(s =>
        {
            int index = required.BinarySearch(s);
            if (index >= 0) return true; //exact match
            index = ~index;
            if (index == 0) return false;
            return s.StartsWith(required[index - 1]);
        });
        foreach (string m in matching)
        {
            Console.WriteLine(m);
        }
    }
    

    给定n = required.Countm = required.Count,接受的答案算法复杂度为O(n*m)。但是我建议的算法复杂度更高:O((n+m)*Log(n))

    【讨论】:

    【解决方案3】:

    此查询查找两个列表中存在的任何匹配项。如果两个列表中都存在一个值,则返回true,否则返回false

    List<string> listString1 = new List<string>();
    List<string> listString2 = new List<string>();
    
    listString1.Add("A");
    listString1.Add("B");
    listString1.Add("C");
    listString1.Add("D");
    listString1.Add("E");
    
    listString2.Add("C");
    listString2.Add("X");
    listString2.Add("Y");
    listString2.Add("Z");
    
    bool isItemExist = listString1.Any(x => listString2.Contains(x));
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2018-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-11
      相关资源
      最近更新 更多