我有逗号分隔的Id值,如下所示:3,4,5,7
,这对于表中的每个记录都有所不同。
现在从配置设置中有特定的值,如:3,4
我需要的代码只选择与配置值匹配的记录:3,4
您可以使用string.split
将逗号分隔值的字符串转换为单个值的列表。
然后,您可以使用linq查找一个列表中也在另一个列表中的所有值。
var results = tableValues.Where(t => configValues.Contains(t));
Foreach元素,你拆分它然后你搜索你的键。试试这个:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
private static List<string> lstStr = new List<string>
{
"1,2,3,4",
"3,4,5",
"3,4,5,6,7,8,9"
};
private static string[] search = new[]{"3", "4"}; // "3,4".Split(',')
public static void Main()
{
foreach(var el in lstStr.Where(x => SearchFunction(x, search)))
{
Console.WriteLine(el);
}
}
private static bool SearchFunction(string listItem, string[] search)
{
var hashSet = listItem.Split(',').ToHashSet();
return search.All(hashSet.Contains);
}
}