gpt4 book ai didi

c# - 在 C# 中对队列进行排序

转载 作者:太空狗 更新时间:2023-10-29 23:57:28 25 4
gpt4 key购买 nike

尽管这个问题听起来很重复,但我搜索了很多但找不到合适的解决方案。

我有以下类(class)

public enum ChangeType
{
Add,
Modify,
Delete
}



public enum ChangedObjectType
{
Project,
Customer,
Border,
Photo
}

public struct ChangeInfo
{
public ChangeType typeofChange { get; private set; }
public ChangedObjectType objectType { get; private set; }

public string objectID { get; private set; }

public ChangeInfo(ChangeType changeType, ChangedObjectType changeObj, string objectId):this()
{
typeofChange = changeType;
objectType = changeObj;
objectID = objectId;
}

}

主题:

public class ChangeInfoUploader
{
static Queue<ChangeInfo> changeInfoQueue = new Queue<ChangeInfo>();
static Thread changeInfoUploaderThread = new Thread(new ThreadStart(ChangeInfoUploaderProc));
static bool isStarted = false;
static Project currentProject;

public static void Initialize(Project curproject)
{
currentProject = curproject;
isStarted = true;
changeInfoUploaderThread.Start();
ResumeData();
}

static void ChangeInfoUploaderProc()
{
while (isStarted)
{
if (currentProject != null)
{
ChangeInfo? addToDb = null;

// I need to sort changeInfoQueue before dequeue
lock (changeInfoQueue)
{
if (changeInfoQueue.Count != 0)
addToDb = changeInfoQueue.Dequeue();
}
}
}
Logdata();
changeInfoUploaderThread.Abort();
}
}

这里是changeInfoQueue队列的示例数据。

<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0005" />
<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0006" />
<Info TypeofChange="Add" ObjectType="Customer" ObjectId="0007" />
<Info TypeofChange="Add" ObjectType="Photo" ObjectId="01a243f5-4894-4d99-8238-9c4cd3" />

我的问题:

  • 我需要根据 ObjectType 整理 changeInfoQueue。我该怎么做?

我的发现:

  • 我找到了 OrderBy .可以使用吗?如果是,怎么做?

除此之外,我还发现了 priorityQueue。什么是最适合我的解决方案?

编辑:

创建相关对象时添加此队列的值。 (项目、边框等)并将其保存在本地 XML 文件中。之后它需要写入数据库。这是通过使用一个线程来完成的,当我们保存这些数据时,它必须以特定的顺序保存,以避免违反外键。所以这个线程就是用来调用那些相关方法的。

我使用 orderby 如下:

Queue<ChangeInfo> changeInfoQueue2 = changeInfoQueue.OrderBy(ChangeInfo => ChangeInfo.ObjectType);

然后它抛出以下异常:

无法将类型“System.Linq.IOrderedEnumerable”隐式转换为“System.Collections.Generic.Queue”。存在显式转换(是否缺少强制转换?)

最佳答案

为什么要按队列中对象的类型排序?队列,根据其定义,并不意味着以这种方式排序,而是旨在作为一种先进先出的元素工作。

如果您只想要一个能够被排序的集合和有序列表,请使用列表,或者为您拥有的不同类型的对象创建多个队列。

例如,如果你去超市,你有几个队列,每个不同的部分一个......将所有人放在同一个队列中然后根据是否“排序”他们是没有任何意义的他们在屠夫或面包店。

当您需要对事物进行“排队”时,您有一个队列……如果您没有使用适当的构造,请不要试图将其强行放入队列。 (“如果你有一把锤子,一切看起来都像钉子”......但它不应该)

关于c# - 在 C# 中对队列进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14396657/

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