簡體   English   中英

如何在C#中使用linq查詢將文本框中的值與字典進行匹配,並在按鈕單擊時在另一個文本框中顯示它

[英]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");

需要linq查詢以從textbox1獲取密鑰並將其與字典匹配,然后將匹配值顯示到textbox2中,這必須在單擊按鈕時完成。

以下代碼不帶linq使用。 我需要使用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]);
        }

您可以使用

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);
        }
    }
}

輸出:

AMBASAMUDRAM

使用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);

輸出:

AMBASAMUDRAM

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM