c# - 字符串列表包含所有子组件
问题描述
字符串列表 G 是:
[0] : {"1,2,5"}
[1] : {"1,2,4,5,6"}
[2] : {"2,4,6"}
[3] : {"1,4,6"}
通过以下命令,我们得出结论"1,4"
存在于列表 G[3] 中:
if (G[i].Contains("1,4")) { //code here }
如何修改上述命令,除了功能(包含),"1,4"
存在于列表 G[1] 中?
程序代码
for (int i = 0; i < candid.Count; i++)
{
foreach (TransactionTP b in transactions)
{
string search = candid[i];
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int j = 0; j < G.Count; j++)
{
IEnumerable<int> numbers = G[j].Split(',').Select(int.Parse);
int idx = 0;
foreach (var number in numbers)
{
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
arraye[i] = arraye[i] + (b.transactionUtility);
break;
}
}
}
}
}
更新:
搜索词的顺序很重要。
解决方案
为了保持你匹配的集合的顺序(在这种情况下是 4,1),你需要评估每个字符串,跟踪你在匹配中的位置。
string[] G = new[]
{
"1,2,5",
"1,2,4,5,6",
"2,4,6",
"1,4,6"
};
string search = "1,4";
var searchNumbers = search.Split(',').Select(int.Parse).ToList();
for (int i = 0; i < G.Length; i++)
{
// Convert the string into an enumeration of numbers
IEnumerable<int> numbers = G[i].Split(',').Select(int.Parse);
// Index to keep track of the search
int idx = 0;
// Loop through the input set sequentially
foreach (var number in numbers)
{
// Check if the input matches the next expected number
if (number == searchNumbers[idx])
{
idx++;
}
if (idx == searchNumbers.Count)
{
Console.WriteLine("String {0} matched", G[i]);
break;
}
}
}
推荐阅读
- postgresql - Quarkus JPA Postgres 存储过程调用 - 使用 CALL 错误
- android - 如何在所有组件上添加加载视图
- angular - 如何在数组上查找最小值、最大值以及如何使用角度更改最小值绿色和最大值红色的颜色文本
- java - 如何从 Spring Boot 向 Outlook 日历添加事件?
- azure - 用于 Cordova 10 的 cordova-plugin-ms-azure-mobile-apps
- python - 在 pandas 中将时间序列数据一分为二时出错
- java - 在 onSetUp 中检测到 EDT 违规时,如何使 AssertJ Swing 测试失败?
- javascript - 使用 Javascript Map 和 Reduce 操作对象数组
- animation - 使用 mvvmcross 以 xamarin 形式显示页面动画
- javascript - 将 config.name 添加到 const sequelize = new Sequelize() 时出错