我正在使用Compact Framework 3.5
myfile.cs
public class Cases : IEnumerable
{
private Hashtable cases = new Hashtable(); // hashtable initilized
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return cases.GetEnumerator();
}
public bool Add(string caseCode, string scanTime)
{
Reading reading = new Reading(caseCode, scanTime);
cases.Add(caseCode, reading);
//some other logic
}
}
我已经将哈希表初始化为cases。我在cases变量中添加了扫描条形码。当前它没有任何顺序。我需要按升序对扫描的条形码代码进行排序。
更新:
例如,我添加以下项目,
Cases a = new Cases();
a.Add("11115", "2014-09-11T01:55:25.0000000-07:00");
a.Add("11111", "2014-09-11T01:55:40.0000000-07:00");
a.Add("11112", "2014-09-11T01:55:45.0000000-07:00");
a.Add("11110", "2014-09-11T01:55:56.0000000-07:00");
a.Add("11113", "2014-09-11T01:56:10.0000000-07:00");
a.Add("11111", "2014-09-11T01:56:17.0000000-07:00");
我希望数据以与列表中相同的顺序打印。这里给出的关键是时间,这里时间默认是升序。但是在打印过程中,打印时是这样的,
[11110,StackOverflow.Reading]
[11111,StackOverflow.Reading]
[11111,StackOverflow.Reading]
[11112,StackOverflow.Reading]
[11113,StackOverflow.Reading]
[11115,StackOverflow.Reading]
我希望这样打印
[11115,StackOverflow.Reading]
[11111,StackOverflow.Reading]
[11112,StackOverflow.Reading]
[11110,StackOverflow.Reading]
[11113,StackOverflow.Reading]
[11111,StackOverflow.Reading]
使用哈希表以随机方式而不是任何顺序打印上述内容,但是SortedList是按升序打印的。您能告诉我如何以相同的顺序打印列表中的数据吗?
最佳答案
使用Dictionary
。
下面的程序实现了您想要的行为-按Reading.scanTime
排序。
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
namespace StackOverflow
{
class Program
{
static void Main(string[] args)
{
Cases a = new Cases();
a.Add("keyA", "01:00");
a.Add("keyB", "11:30");
a.Add("keyC", "06:20");
foreach (KeyValuePair<string, Reading> x in a)
{
Console.WriteLine("{0}: {1}", x.Key, x.Value);
}
}
}
public class Cases : IEnumerable
{
private Dictionary<string, Reading> cases =
new Dictionary<string, Reading>();
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return cases.GetEnumerator();
}
public bool Add(string caseCode, string scanTime)
{
Reading reading = new Reading(caseCode, scanTime);
cases.Add(caseCode, reading);
cases = cases.Values.OrderBy(v => v).ToDictionary(r => r.caseCode);
return true;
}
}
public class Reading : IComparable
{
public string caseCode; // don't mind public fields and bad naming, it's just an example ;)
public string scanTime;
public Reading(string a, string b)
{
this.caseCode = a;
this.scanTime = b;
}
public int CompareTo(object obj)
{
Reading other = obj as Reading;
if (other == null)
{
return -1;
}
return this.scanTime.CompareTo(other.scanTime);
}
public override string ToString()
{
return caseCode + " scanned at " + scanTime;
}
}
}
关于c# - 按ASC顺序中的值对哈希表进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25749777/