Tobias Møller
Tobias Møller

Reputation: 64

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;

Upvotes: 0

Views: 1134

Answers (4)

fubo
fubo

Reputation: 45947

Here is another approach with Array.FindIndex - which performs better than the Linq version

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;

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37299

Use linq's 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.

If using C# 7.0 you can use named tuples:

(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

Upvotes: 2

Saif
Saif

Reputation: 2679

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

working sample

Upvotes: 0

quadroid
quadroid

Reputation: 8940

If i understood the Question correct you want to have the next string containing an "x" in a string array.

 var result = logContent.Select((value, index) => new { index, value })
                        .First(x => x.value.Contains("x");

Upvotes: 1

Related Questions