我有一个字符串和一个字符串列表。我试图返回一个列表,str中包含strList,结果应为4和21。
这是我的代码,不知道我错过了什么。
string str= "21,1,4";
List<string> strList= new List<string> { "4","21" };
var a = str.Where(i => i.ToString().Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries).ToList().Any(s=>strList.Contains(s)));
答案 0 :(得分:4)
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var splitStr = str.Split(',');
var result = splitStr.Where(x => strList.Contains(x));
答案 1 :(得分:1)
string str= "21,1,4";
List<string> strList= new List<string> { "4","21" };
string[] result = str.Split(',');
foreach(string s in result)
if(strList.Contains(s))
Console.WriteLine(s);
简单。
答案 2 :(得分:1)
将这一切保持在一条线上,这似乎是你的目标:
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var a = str.Split(',').Where(s => strList.Contains(s));
a
将是strList
中包含的str(分割后)中所有值的IEnumerable。
答案 3 :(得分:1)
您可以使用Intersect
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
var result = str.Split(',').Intersect(strList);
Console.WriteLine(string.Join(", ", result));
输出:
21,4
代码的问题在于,通过执行str.Where
,您将迭代字符串的字符。您应该只是拆分str
然后迭代它以查找strList
中的匹配项。
答案 4 :(得分:0)
你可以做到
string str = "21,1,4";
List<string> strList = new List<string> { "4", "21" };
List<string> splitList = str.Split(",").ToList();
List<string> overlap = strList.Where(str => splitList.Contains(str)).ToList();
答案 5 :(得分:0)
public partial class PJX_MainWindow : Form
{
private ChromeDriver driver;
private ChromeOptions chromeOptions;
private void PJX_MainWindow_Load(object sender, EventArgs e)
{
chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", @"C:\PJX\SalesReports");
chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
chromeOptions.AddArgument("--disable-extensions");
driver = new ChromeDriver(System.AppDomain.CurrentDomain.BaseDirectory + @"Resources\", chromeOptions);
driver.Manage().Window.Maximize();
string url = "https://www.somepage.com";
driver.Navigate().GoToUrl(url);
}
}
其中 var str = "21,1,4";
var otherStrList = new List<string> { "4", "21" };
var separatedstrList = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
var commonStrings = separatedstrList.Intersect(otherStrList);
是您正在寻找的答案。
答案 6 :(得分:0)
优雅的Join语法怎么样:
var results = (from main in str.Split(',')
join key in strList
on main equals key
select main).ToList();
如果您要删除重复项(如果.Distinct()
有重复项),您可以在.ToList()
之前添加str
。