我只需要获取查询的第一个值。我怎样才能做到这一点 ?

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;

如果我使用限制,我会收到错误消息。那么有什么其他方法可以限制输出或如何从查询中单独获得第一个结果?

最佳答案

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

var key = dict.FirstOrDefault(v => v.Value == "Peter").Key;

编辑:添加了便于理解/复制粘贴的代码...
雷克斯特 - 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() 之间的这种细微差别)

关于c# - 如何从查询 c# 中获取有限数量的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50673982/

10-17 00:57
查看更多