【问题标题】:how do i display a key (only)from a sorted list?如何显示排序列表中的键(仅)?
【发布时间】:2018-06-08 02:42:41
【问题描述】:

我正在尝试确定在每个标签上显示随机键的正确语法。

//declare random
Random rnd = new Random();

//create the sorted list and add items
SortedList<string,string> sl = new SortedList<string,string>();
sl.Add("PicknPay", "jam");
sl.Add("Spar", "bread");
sl.Add("Checkers", "rice");
sl.Add("Shoprite", "potato");
sl.Add("Cambridge", "spinash");

int Count = 0;
int nValue = rnd.Next(5);
int newindex = 0;
int seekindex;

for (seekindex = 0; seekindex > nValue; seekindex++)
{
    newindex =  rnd.Next(seekindex);
}

lbl1.Text = "";

foreach (var item in sl.Keys) 
{
    lbl1.Text += "," + Convert.ToString(item.IndexOf(item));
}

lbl1.Text = lbl1.Text.TrimStart(',');

【问题讨论】:

  • 您是否尝试从您的SortedList 中选择一个唯一的随机键来显示在三个标签中的每一个中?您的代码表明您正在尝试在lbl1.Text 中显示所有这些,用逗号分隔。
  • 我不确定我是否理解正确。您想在自己的标签中显示sl 中的每个Key 吗?
  • 如果您想随机打乱您的排序列表,您可以在第二次为每个stackoverflow.com/a/4262134/3254405 使用 linq order by
  • 表单加载时。这三个标签应该显示一个从排序列表中随机选择的键...例如,当表单加载时,标签 1 将显示“spar”,标签 2 显示“shopright”,label3 显示 cambridge,但如果再次加载表单,则应该选择上面随机的不同键

标签: c# collections labels keyvaluepair


【解决方案1】:

一种方法是通过调用System.Linq 扩展方法OrderBy 并传递从Random.Next() 返回的值来获取随机排序的键列表,然后从这个随机列表中取出前三个项目:

SortedList<string, string> sl = new SortedList<string, string>
{
    {"PicknPay", "jam"},
    {"Spar", "bread"},
    {"Checkers", "rice"},
    {"Shoprite", "potato"},
    {"Cambridge", "spinash"}
};

var rnd = new Random();
var shuffledKeys = sl.Keys.OrderBy(key => rnd.Next()).ToList();

lbl1.Text = shuffledKeys[0];
lbl2.Text = shuffledKeys[1];
lbl3.Text = shuffledKeys[2];

【讨论】:

  • 我不知道OrderBy(key =&gt; rnd.NextDouble())。巧妙的技巧,将添加到我的“提示和技巧”中,谢谢!
  • 谢谢@Rufus L 谢谢你,你的传奇,你做得这么简单.. 我的教科书很没用,他们没有正确解释。我谦虚地请求你给我推荐一本书,它可以正确地教给我我需要学习的东西。
  • 有一个问题,为什么是NextDouble() 而不是Next()
  • @MO_Tries 恐怕我目前无法推荐任何书籍——我主要是在工作和在线学习。我的建议是继续玩小项目,多问问题,你会成功的!
  • @Sach Next() 也可以,而且效率可能更高一些。我将更改示例。
猜你喜欢
  • 2014-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多