在字符串中,我需要根据列表中任何项目的第一个匹配来恢复7个char子字符串。如果没有匹配,则应该返回一个空字符串。
我有以下代码:
List<string> myList = new List<string>()
{
"TNCO",
"TNCB",
"TNIT"
};
string sample = "TNSD102, WHRK301, TNIT301, YTRE234";
//doesn't give an index
bool anyfound = myList.Any(w => sample.Contains(w));
//code that needs replacing
string code = sample.Substring(sample.IndexOf("TNC"), 7);
if (code == "")
{
code = sample.Substring(sample.IndexOf("TNIT"), 7);
}
该列表永远不可能超过35-40个项目和字符串&lt; 50个字符。
任何人都能指出我正确的方向吗?
答案 0 :(得分:2)
string val1 = (sample.Split(',').FirstOrDefault(w => myList.Any(m => w.Contains(m))) ?? string.Empty).Trim();
答案 1 :(得分:1)
这为您提供了所有匹配的IEnumerable:
var matches = from code in sample.Split(',')
from w in myList
where code.Trim().StartsWith(w)
select code;
要获得第一个值,请使用FirstOrDefault。如果没有匹配,则使用coalesce运算符??
返回空字符串。
string firstMatch = (matches.FirstOrDefault() ?? "").Trim();
答案 2 :(得分:0)
如果数据集很小,您可以简单地拆分字符串并搜索第一个匹配项:
// split the sample string into separate entries
var entries = sample.Split(new char[] {',', ' '},
StringSplitOptions.RemoveEmptyEntries);
// find the first entry starting with any allowed prefix
var firstMatch = entries.FirstOrDefault (
e => myList.Any (l => e.StartsWith(l)));
// FirstOrDefault returns null if there are no matches
if (firstMatch == null)
Console.WriteLine("No match!");
else
Console.WriteLine(firstMatch);
示例输出(DEMO):
TNIT301
答案 3 :(得分:0)
此处运行此代码会根据您要查找的内容返回索引2。
int keyIndex = myList.FindIndex(w => samples.Contains(w));
TNIT301
这是索引字符串值
您还可以执行以下操作以返回keyIndex
变量值的索引位置的字符串值。
var subStrValue = samples.Split(',')[keyIndex];
答案 4 :(得分:0)
List<string> myList = new List<string> { "TNCO", "TNCB", "TNIT" };
string sample = "TNSD102, WHRK301, TNIT301, YTRE234";
string[] sampleItems = sample.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var results = myList
.Select(prefix => sampleItems
.FirstOrDefault(item => item.StartsWith(prefix)) ?? "");