问题描述
我尝试浏览其他一些问题,但找不到与部分问题匹配的任何问题.
I tried looking through some of the other questions, but couldn't find any that did a partial match.
我有两个List<string>
其中包含代码.一个是所选代码的列表,一个是必需代码的列表.整个代码列表都是一棵树,因此它们具有子代码.一个例子是代码B代码B.1代码B.11
They have codes in them. One is a list of selected codes, one is a list of required codes. The entire code list is a tree though, so they have sub codes. An example would beCode BCode B.1Code B.11
所以可以说,必填代码为B,但是树下的任何内容都可以满足该要求,因此,如果选择的代码"为A和C,则匹配将失败,但是如果选择的代码之一为B.1,则该匹配代码将包含部分匹配.
So lets say the Required code is B, but anything under it's tree will meet that requirement, so if the Selected codes are A and C the match would fail, but if one of the selected codes was B.1 it contains the partial match.
我只需要知道所选的任何代码是否与所需的任何代码部分匹配.这是我目前的尝试.
I just need to know if any of the selected codes partially match any of the required codes. Here is my current attempt at this.
//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转换为字符串.
The error I get is on the Required.Any() and it's cannot convert from bool to string.
抱歉,如果这令人困惑,请告知我是否添加任何其他信息会有所帮助.
Sorry if this is confusing, let me know if adding any additional information would help.
推荐答案
我认为您需要这样的东西:
I think you need something like this:
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
,这取决于您的要求.
Applying the Any
condition on required
in this way should give you the elements that match - I'm not sure if you should use StartsWith
or Contains
, that depends on your requirements.
这篇关于使用Linq比较两个列表进行部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!