c# - 如何从查询c#中获取有限数量的输出
问题描述
我只需要获取查询的第一个值。我怎样才能做到这一点 ?
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Jack");
dict.Add(2, "Peter");
dict.Add(3, "Chris");
dict.Add(4, "Peter");
var keys = from entry in dict where entry.Value == "Peter" select entry.Key limit 1;
如果我使用限制,我会得到一个错误。那么还有什么其他方法可以限制输出或如何单独从查询中获取第一个结果?
错误 CS0103 当前上下文中不存在名称“limit”
解决方案
你也可以试试这个语法......
var key = dict.FirstOrDefault(v => v.Value == "Peter").Key;
编辑:添加代码以便于理解/复制粘贴... Rextester - http://rextester.com/AIAKRZ95654
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
Dictionary<int, string> dict = new Dictionary<int, string>();
dict.Add(1, "Jack");
dict.Add(2, "Peter");
dict.Add(3, "Chris");
dict.Add(4, "Peter");
var key = dict.FirstOrDefault(v => v.Value == "Peter").Key;
Console.WriteLine(key);
}
}
}
更新:请注意,使用FirstOrDefault()
关键字时,?.key
不是必需的,最坏的情况下它会返回0
. 使用?.key
时需要First()
。由于这种混淆,Flater 否决了这个答案,并从下面的评论部分删除了他的评论。(他可能应该承认并提到这个因素,以便让其他程序员对First()
和之间的这种细微差别有一个警告/警告标志FirstOrDefault()
)
推荐阅读
- angular - 带有**的Angular 9路由器重定向无法正常工作
- neo4j - “在建立安全 TLS 连接之前断开客户端网络套接字” - Neo4j/GraphQL
- c++ - 如果字符串向量中的单词在前面,则删除字符
- reactjs - Javascript - 通过 array.map() 返回两个输出
- deep-learning - 尽管只消耗了 60% 的内存,但 Cuda 内存不足
- google-apps-script - 我可以付费提高我的 Google App Scripts 配额限制吗?
- git - 是否需要在 github 中设置 SSH-Key?
- c# - 无法点击登录按钮
- linux - 如何在单引号或双引号中加入每个换行字符串
- python - Python3:帮助 - 脚本过于复杂