How to access specific data as a result of LINQ query?

I know this is very easy for you guys. Please consider the following code:

string[] str = { "dataReader", "dataTable", "gridView", "textBox", "bool" };

            var s = from n in str
                    where n.StartsWith("data")
                    select n;

            foreach (var x in s)
            {
                Console.WriteLine(x.ToString());
            }
            Console.ReadLine();

Presumably he will print:

dataReader
dataTable

right?

What if, for example, I don’t know the data and what the results of the query will be (but I’m sure that it will return some results), and I just want to print the second one , which will be created upon request, should my code instead of use foreach?

Is there something like indexing an array here?

+3
source share
2 answers

You are looking for Enumerable.ElementAt.

var secondMatch = str.Where(item => item.StartsWith("data")) //consider null-test
                     .ElementAt(1); 

Console.WriteLine(secondMatch); //ToString() is redundant

Where , - , (, ).

, , , , ElementAtOrDefault.

var secondMatch = str.Where(item => item.StartsWith("data"))
                     .ElementAtOrDefault(1); 

if(secondMatch == null) // because default(string) == null
{
   // There are no matches or just a single match..
}
else
{
  // Second match found..
}

, , , ... . , , , , , , .

var secondMatch = str.Where(item => item.StartsWith("data"))
                     .ToArray()[1]; //ElementAt will will work too
+7

:

s.Skip(1).First();
s.ElementAt(1);

, X, y. , .

+6

Source: https://habr.com/ru/post/1769541/


All Articles