[英]How to match value from textbox to dictionary and display it in another textbox on button click with linq query in C#
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(04634, "AMBASAMUDRAM");
dictionary.Add(04253, "ANAMALI");
dictionary.Add(04153, "ARAKANDANALLUR");
Need linq query to get the key from textbox1 and match it to dictionary and displays the match value into textbox2 and this must be done on button click. 需要linq查询以从textbox1获取密钥并将其与字典匹配,然后将匹配值显示到textbox2中,这必须在单击按钮时完成。
The below code is used without linq. 以下代码不带linq使用。 And i need the same to done with the Linq Query.
我需要使用Linq查询完成相同的操作。
private void button1_Click(object sender, EventArgs e)
{
string std = DoWork(Convert.ToInt32(textBox1.Text));
textBox2.Text = std;
}
public string DoWork(int stdcode)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(04634, "AMBASAMUDRAM");
dictionary.Add(04253, "ANAMALI");
dictionary.Add(04153, "ARAKANDANALLUR");
dictionary.Add(04371, "ARANTANGI");
dictionary.Add(04320, "ARAVAKURICHI");
dictionary.Add(04329, "ARIYALUR");
return (dictionary[stdcode]);
}
You can use 您可以使用
var fooDict= dictionary .Where(a=> a.Value == "AMBASAMUDRAM") var fooDict = dictionary .Where(a => a.Value ==“ AMBASAMUDRAM”)
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Use a dictionary with an int key.
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(04634, "AMBASAMUDRAM");
dictionary.Add(04253, "ANAMALI");
dictionary.Add(04153, "ARAKANDANALLUR");
// You can look up the int in the dictionary.
if (dictionary.ContainsKey(04634))
{
String value = dictionary[04634];
Console.WriteLine(value);
}
}
}
Output: 输出:
AMBASAMUDRAM
Using LINQ: 使用LINQ:
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(04634, "AMBASAMUDRAM");
dictionary.Add(04253, "ANAMALI");
dictionary.Add(04153, "ARAKANDANALLUR");
var value = dictionary.FirstOrDefault(x=>x.Key.Contains(04634)).Value;
Console.WriteLine(value);
Output: 输出:
AMBASAMUDRAM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.