gpt4 book ai didi

c# - 按 ASC 顺序按值对哈希表进行排序

转载 作者:行者123 更新时间:2023-11-30 19:39:54 24 4
gpt4 key购买 nike

我正在使用 compact framework 3.5

我的文件.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 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com