如何将哈希表中的值添加到字符串列表? (C#) [英] How do I add a value in a hash table to a string list? (C#)

查看:44
本文介绍了如何将哈希表中的值添加到字符串列表? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含我的tcpUsers的哈希表,我想将它输出到一个字符串列表,作为管理当前连接用户的简单方法。我该怎么做还有其他更方便的方法吗?



我尝试过:



我我不确定从哪里开始,但我想在列表中添加一个值,可能是下一个可用的索引?

I have a hashtable which is containing my tcpUsers, and i want to output this to a string list as an easy way to manage currently connect users. How would I do this. Any other easier method?

What I have tried:

I'm not sure where to start, but i want to just add a value onto the list, maybe into the next available index?

推荐答案

如果你需要显示这个对某些用户的信息然后最好是转换并设置有用控件的DataSource属性。在示例中,我使用了数据网格视图,因为这通常适用于显示表数据。



显示示例:



If you need to display this information to some users then it would be best to cast and set a DataSource property of a useful control. In the example i used a data grid view since this is usually right for displaying table data.

Example for displaying:

class Person {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public int Age { get; set; }
     public bool Current { get; set; }
}

HashTable table = new HashTable();
table["4874"] = new Person() {
   FirstName = "Berny",
   LastName = "Sanders",
   Age = 65,
   Current = true
};

table["6451"] = new Person() {
   FirstName = "Michelle",
   LastName = "Obama",
   Age = 50,
   Current = false
};

// The below assumes your using a data grid view with four columns, having the DataPropertyNames set to the same name as the Column name. If they are different, a new column will be added for each DataPropertyName not set.
dataGridView1.DataSource = table.Cast<DictionaryEntry>().Select(x => new {
    Column1_FirstName = ((Person)x.Value).FirstName,
    Column2_LastName = ((Person)x.Value).LastName,
    Column3_Age = ((Person)x.Value).Age,
    Column4_Current = ((Person)x.Value).Current
}).Reverse().ToList();

OUTPUT::

FirstName | LastName | Age | Current
Berny     | Sanders  | 65  |  True
Michelle  |  Obama   | 50  |  False

Note the use of Reverse().  Calling ToList() on a cast of the Hashtable will read from bottom up, so to keep the order (though the order is not guaranteed), call reverse().


这篇关于如何将哈希表中的值添加到字符串列表? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆