簡體   English   中英

如何使用linq查詢分別從列表中獲取鍵和值

[英]How to get both key and value from list separately with linq query

調試屏幕截圖 我開始使用隨機數組進行測驗,但是在完成這項工作后,我意識到我無法追蹤用戶選擇的答案。 有人向我展示了如何使用一些隨機播放算法,但這使我感到困惑。

因此,我決定創建一個List<KeyValuePair>來保存我的數據集中的答案,該鍵是一個用於數據集行的字符串,並且值是一個整數,即正確答案為1,錯誤答案為0。

所以我正在做的是,我有四個用css風格化的按鈕,我正在將按鈕文本變成四個答案之一。 這聽起來像是不好的編程習慣,但我唯一能想到的就是將Tab順序屬性更改為1或0,這樣我就可以跟蹤答案以顯示在結果頁的最后。

我正在使用的代碼是這樣的...

ds = MyDs(1);

System.Random rnd = new System.Random();

var QA = new List<KeyValuePair<string,int>>();

QA.Add(new KeyValuePair<string, int>(ds.Tables[0].Rows[0]["CorrectAnswer"].ToString(),1));
QA.Add(new KeyValuePair<string, int>(ds.Tables[0].Rows[0]["WrongAnswer1"].ToString(), 0));
QA.Add(new KeyValuePair<string, int>(ds.Tables[0].Rows[0]["WrongAnswer2"].ToString(), 0));
QA.Add(new KeyValuePair<string, int>(ds.Tables[0].Rows[0]["WrongAnswer3"].ToString(), 0));

var myQa = QA.OrderBy(c=> rnd.Next()).Select(c=>c.Key.ToString()).ToList();

Label5.Text = ds.Tables[0].Rows[0]["Question"].ToString();

Button1.Text = myQa[0].ToString();
Button2.Text = myQa[1].ToString();
Button3.Text = myQa[2].ToString();
Button4.Text = myQa[3].ToString();

當您查看myQa時這很好,密鑰會像應該的那樣顯示,但是如果我這樣做的話...

var myQa = QA.OrderBy(c=> rnd.Next()).Select(c=>c.Key.ToString() + c.Value.ToString()).ToList();

然后我的按鈕文本將鍵和值添加到文本中,我不希望那樣,我只想將鍵顯示在按鈕文本中,然后能夠訪問其值。

有什么想法或我想念的地方嗎? 我假設它在我的查詢中,我不確定如何修復它。

謝謝

從根本上講,您需要一個Dictionary<TKey, TValue>

這里:

var myQa = QA.OrderBy(c=> rnd.Next()).Select(c=>c.Key.ToString() + c.Value.ToString()).ToList();

您同時選擇key及其value 相反,您可以執行以下操作:

var myQa = QA.OrderBy(c=> rnd.Next()).Select(c=>c.Key.ToString()).ToList(); 得到鑰匙

var kValue = QA.Where(m=> m.Key == "Correct Answer").FirstOrDefault().Value; <-willl為您提供特定鍵的值。

實際上,您可以使用ToDictionary方法代替ToList。 它接受鍵選擇器和值選擇器參數。 而你可以

   var myQa = QA.OrderBy(c=> rnd.Next()).ToDictionary(ks=>ks.Key.ToString(), vs=>vs..Value.ToString());
   foreach(var keyValuePair in myQa)
   {
       Button button = new Button();
       button.Text = keyValuePair.Key;
       button.Tag= keyValuePair.Value;
       SomeParentControl.Controls.Add(button);
   }

這樣,您將在一個枚舉中同時擁有鍵和值。

您也可以這樣:

   var myQaButtons = QA.OrderBy(c=> rnd.Next()).Select(c=>new Button{Text = c.Key, Tag = c.Value}).ToList();
   myQaButtons.ForEach(b=>SomeParentControl.Controls.Add(b));

或者簡單地

   var myQa = QA.OrderBy(c=> rnd.Next()).Select(c=>new {c.Key, c.Value}).ToList();

   Button1.Text = myQa[0].Key;
   Button1.Tag = myQa[0].Value
   Button2.Text = myQa[1].Key;
   Button2.Tag = myQa[1].Value;
   Button3.Text = myQa[2].Key;
   Button3.Tag = myQa[2].Value;
   Button4.Text = myQa[3].Key;
   Button4.Tag = myQa[3].Value;

暫無
暫無

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

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