我知道,这对你们来说很简单。 请考虑以下代码:
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();
据推测,它将打印:
dataReader
dataTable
对吗?
如果我不知道数据,也不知道查询的结果是什么(但我确定它会返回一些结果),我只想打印第二个 将由查询生成的项目,我的代码应该是什么而不是使用 foreach
?
这里有数组索引之类的东西吗?
最佳答案
您正在寻找 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
关于c# - 如何访问 LINQ 查询结果中的特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3933341/