首页 > 解决方案 > 如何从查询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”

标签: c#

解决方案


你也可以试试这个语法......

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()


推荐阅读