简体   繁体   English

如何在LINQ查询结果中访问特定数据?

[英]How to access a particular data in LINQ query result?

I know, this is very simple 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();

Supposedly, it 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 it will return some results) and I just want to print the second item that will be produced by the query, what should my code be instead of using foreach ? 例如,如果我不知道数据,以及查询的结果是什么(但我确定它会返回一些结果),我只想打印查询将生成的第二个项目,我的代码应该是什么而不是使用foreach

Is there something like array-indexing here? 这里有像数组索引这样的东西吗?

You're looking for Enumerable.ElementAt . 您正在寻找Enumerable.ElementAt

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

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

Since Where streams its results, this will be efficient - enumeration of the source sequence will be discontinued after the second match (the one you're interested in) has been found. 由于Where流式传输其结果,这将是有效的 - 源序列的枚举将在第二次匹配(您感兴趣的那个)之后被中断。

If you find that the implicit guarantee you have that the source will contain two matches is not valid, you can use ElementAtOrDefault . 如果你发现你有一个源包含两场比赛的隐性担保是无效的,可以使用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..
}

You could use array-indexing here as you say, but only after you load the results into... an array. 可以在这里使用数组索引,但只有在将结果加载到...数组后才能使用。 This will of course mean that the entire source sequence has to be enumerated and the matches loaded into the array, so it's a bit of a waste if you are only interested in the second match. 这当然意味着必须枚举整个源序列并将匹配加载到数组中,所以如果您只对第二场比赛感兴趣,那就有点浪费了。

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

you got a few options: 你有几个选择:

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

The first is more suited for scenarios where you want X elements but after the y first elements. 第一个更适合您想要X元素但在y个第一个元素之后的场景。 The second is more clear when you just need a single element on a specific location 当您在特定位置需要单个元素时,第二个更清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM