I need to get only the first value of the query. How can I do that ?
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;
I get an error if I use limit. So what is other ways to limit the output or how to get the first result alone from the query ?
Error CS0103 The name 'limit' does not exist in the current context
You could also try this syntax...
var key = dict.FirstOrDefault(v => v.Value == "Peter").Key;
Edit: Added code for ease of understanding / copy-pasting... 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);
}
}
}
UPDATE: Please note when using FirstOrDefault()
keyword, ?.key
is not required, worst case it will return 0
. The ?.key
is required when using First()
. Because of this confusion Flater voted this answer down, and deleted his comments from the comment section below. (He probably should have acknowledge and mentioned this factor to give other programmers a heads up / caution sign about this subtle difference between First()
and FirstOrDefault()
)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments