我试着查看其他一些问题,但找不到任何部分匹配.
我有两个 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();
Run Code Online (Sandbox Code Playgroud)
我得到的错误是在Required.Any()上,它无法从bool转换为字符串.
对不起,如果这令人困惑,请告诉我是否添加任何其他信息会有所帮助.
我想你需要这样的东西:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
以这种方式应用Any条件required应该给你匹配的元素 - 我不确定你是否应该使用StartsWith或Contains,这取决于你的要求.