如何输出字典的前n个元素(在单独的标签中)? [英] How can I output the first n elements of a dictionary (in separate labels)?
本文介绍了如何输出字典的前n个元素(在单独的标签中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
到目前为止,我所拥有的是:
So far here's what I have:
string[] modes = {"AA", "BB", "CC"};
Label[] aName = new Label[5];
aName[0] = lblName1;
//Store label from form
//So on & so forth
for (int y = 0; y < modes.Length; y++)
{
switch (modes[y])
{
case "AA":
foreach (KeyValuePair<string, int> pair in dictionaryA)
//tried foreach (KeyValuePair<string, int> pair in dictionaryA).Take(5)), but it did not work?
{
u++;
if (u == 5)
{
return;
}
aName[u].Text = pair.Key.ToString().ToUpper();
}
break;
.
.
.
.
}
}
我只需要获得字典的前5项并输出每个项目单独的标签。代码结构看起来很荒谬,但这些只是基于我对C#的基本知识的假设。 :D:)
I need to get only the first 5 items of the Dictionary and output each item to separate labels. The code structure looks ridiculous but these are only my assumptions based on the basic knowledge I have of C#. :D :)
推荐答案
我会使用进行
循环,例如
I would use afor
loop, e.g.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("a", 1);
dict.Add("b", 2);
dict.Add("c", 3);
for (int index = 0; index < 5 && index < dict.Count; index++)
{
Console.WriteLine(dict.ElementAt(index).Key.ToUpper());
}
我已经使用控制台应用程序修改了您的代码以进行演示并且工作正常。希望这对您有所帮助: - )
I have modified your code with a console application to demonstrate and it works fine.Hope this helps to you :-)
static Dictionary<string,> myDictionary = new Dictionary<string,>();
static void Main(string[] args)
{
myDictionary.Add("1", 4);
myDictionary.Add("2", 3);
myDictionary.Add("3", 1);
myDictionary.Add("4", 5);
myDictionary.Add("5", 6);
myDictionary.Add("6", 7);
myDictionary.Add("7", 8);
myDictionary.Add("8", 9);
string[] modes = { "AA", "BB", "CC" };
string[] arr = new string[5];
int u = 0;
for (int y = 0; y < modes.Length; y++)
{
switch (modes[y])
{
case "AA":
foreach (KeyValuePair<string,> pair in myDictionary)
{
if (u < 5)
{
arr[u] = pair.Key.ToString().ToUpper();
}
else
{
continue;
}
u++;
}
break;
}
}
foreach(string k in arr)
{
Console.WriteLine(k);
}
Console.ReadLine();
}
}
我没有看到你的代码示例有什么问题......但......我无法看到变量'u初始化的位置;我只能假设它的初始值是#0。
这是使用Linq的另一个例子:
I don't see anything wrong with your code example ... but ... I can't see where the variable 'u is initialized; I can only assume it's initial value is #0.
Here's an alternative example using Linq:
private Dictionary<string, int> DictionaryA = new Dictionary<string, int>();
// for testing only
List<Label> ALabelList = new List<Label>();
// for testing only
for (int i = 0; i < 10; i++)
{
DictionaryA.Add(i.ToString(), i);
}
foreach (var kvp in DictionaryA.Take(5))
{
ALabelList.Add(new Label {Text = kvp.Key.ToUpper()});
}
为什么人们可能会避免使用Linq ForEach和All运算符:请参阅Eric Lippert的文章:[ ^ ]。
For reasons why one might avoid using the Linq ForEach, and All operators: see Eric Lippert's article: [^].
这篇关于如何输出字典的前n个元素(在单独的标签中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文