[英]Find index and value of next match in string array
I have been looking for a long time now, to find any smarter solution than mine, to gather index and value of an item in my array. 我一直在寻找很长一段时间,以找到比我的智能解决方案更智能的解决方案,以收集数组中一项的索引和值。 I can not search directly on the item because there will always be some other char in the string. 我不能直接在项目上搜索,因为字符串中总会有其他字符。 Here is an example of what I want to do. 这是我想做的一个例子。
// logcontent = ["f", "red", "frs", "xyr", "frefff", "xdd", "to"]
string lineData = "";
int lineIndex = 0;
foreach (var item in logContent.Select((value, index) => new { index, value }))
{
string line = item.value;
var index = item.index;
if (line.Contains("x"))
{
lineData = line;
lineIndex = index;
break;
}
}
I want to only get the next item 我只想拿下一件
lineData = "xyr";
lineIndex = 3;
Use linq's FirstOrDefault
: 使用linq的FirstOrDefault
:
var result = logContent.Select((value, index) => new { index, value })
.FirstOrDefault(item => item.value.Contains("x"));
If there is no such item you will get null
. 如果没有这样的项目,您将得到null
。
If using C# 7.0 you can use named tuples : 如果使用C#7.0,则可以使用命名元组 :
(int lineIndex, string lineData) = logcontent.Select((value, index) => (index, value))
.FirstOrDefault(item => item.value.Contains("x"));
and then o something with lineIndex
or lineData
directly which is like you would with the original version 然后直接使用lineIndex
或lineData
进行操作,就像使用原始版本一样
If i understood the Question correct you want to have the next string containing an "x" in a string array. 如果我理解正确的问题,则要在字符串数组中包含下一个包含“ x”的字符串。
var result = logContent.Select((value, index) => new { index, value })
.First(x => x.value.Contains("x");
Here is another approach with Array.FindIndex - which performs better than the Linq
version 这是Array.FindIndex的另一种方法-比Linq
版本的性能更好
string[] logContent = { "f", "red", "frs", "xyr", "frefff", "xdd", "to" };
int lineIndex = Array.FindIndex(logContent, x => x.Contains("x"));
string lineData = lineIndex >= 0 ? logContent[lineIndex] : null;
this code 此代码
string[] ogcontent = {"f", "red", "frs", "xyr", "frefff", "xdd", "to"};
string lineData = "";
int lineIndex = 0;
for (int i = 0; i < ogcontent.Length; i++)
{
string line = ogcontent[i];
var index = i;
if (line.Contains("x"))
{
lineData = line;
lineIndex = index;
Console.WriteLine("index = {0}", i);
Console.WriteLine("value = {0}", line);
break;
}
}
result 结果
index = 3
value = xyr
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.