[英]How to find first or last string in list by StartsWith or Contains searching value without adding to another list
I'm trying to understand what variants I can use to get only one string with Contains
or StartsWith
first or last line, which contains searching value or starts with it. 我试图了解哪些变体可用于只Contains
一个包含包含搜索值或以它开头的包含首尾值或StartsWith
首行或最后一行的字符串。 But without creating of new list and taking of first or last line from there, which result is actually answer to this question, but I wondering if it is possible to get it directly from the list, for example if list content is: 但是,如果不创建新列表并从那里获取第一行或最后一行,则实际上是此问题的答案,但是我想知道是否有可能直接从列表中获取它,例如,列表内容是否为:
List<string> list = new List<string>()
{
"data file collection k"
"file name collection l",
"file data collection m",
"name data collection a",
"name data collection b",
"data name collection c",
"data file collection d"
};
and searching word: 和搜索词:
string val = "name";
So this way: 所以这样:
foreach (string str in List)
{
if (str.StartsWith(val))
{
// ...
}
}
result is: 结果是:
name data collection a
name data collection b
or if look for whole string content for example: 或者例如,查找整个字符串内容:
var mtchVal = list.Where(stringToCheck => stringToCheck.Contains(val));
result would be: 结果将是:
file name collection l
name data collection a
name data collection b
data name collection c
but desired result with StartsWith
must be: 但是StartsWith
理想结果必须是:
name data collection a
and by whole content: 并按全部内容:
file name collection l
If linq is allowed then 如果允许使用linq
var list = new List<string>();
var first = list.FirstOrDefault(s => s.StartsWith("name"));
var last = list.LastOrDefault(s => s.StartsWith("name"));
For the StartsWith
case, use 对于StartsWith
案例,请使用
list.FirstOrDefault(stringToCheck => stringToCheck.StartsWith(val));
For the whole string content case, use 对于整个字符串内容,请使用
list.FirstOrDefault(stringToCheck => stringToCheck.Contains(val));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.