Dev*_*evT 4 .net c# queue collections priority-queue
虽然这个问题听起来像是重复的,但我搜索了很多但却找不到合适的解决方案.
我有以下课程
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;
}
}
Run Code Online (Sandbox Code Playgroud)
线程:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是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" />
Run Code Online (Sandbox Code Playgroud)
我的问题 :
我的发现:
除此之外我发现了priorityQueue.对我来说最好的解决方案是什么?
编辑:
创建相关对象时会添加此队列的值.(项目,边框等)并将其保存在本地XML文件中.之后,它需要写入数据库.这是通过使用线程来完成的,当我们保存这些数据时,必须以特定顺序保存它以避免外键冲突.所以这个线程用于调用那些相关的方法.
我使用orderby如下:
Queue<ChangeInfo> changeInfoQueue2 = changeInfoQueue.OrderBy(ChangeInfo => ChangeInfo.ObjectType);
Run Code Online (Sandbox Code Playgroud)
然后抛出以下异常:
无法将类型'System.Linq.IOrderedEnumerable'隐式转换为'System.Collections.Generic.Queue'.存在显式转换(您是否错过了演员?)
Jor*_*oba 14
为什么要按队列中的对象类型进行排序?根据它的定义,一个队列并不意味着以这种方式排序,而是打算作为先出先出的元素.
如果您只想要一个能够被订购的集合,并使用有序列表或为您拥有的不同类型的对象创建多个队列,请使用List.
例如,如果你去超级市场,你有几个队列,每个不同的部分一个...将所有人放在同一个队列然后根据他们是否在"排序"它们没有任何意义对于屠夫或面包店.
当你需要"排队"事物时你有一个队列...如果你不使用适当的构造,不要试图强制它进入队列.("如果你有锤子,一切看起来像钉子"......但它不应该)
虽然有关使用队列的所有内容OrderBy都是有效的,但您仍然可能希望在队列中对元素进行排序.
您可以基于以下内容构建新队列IOrderedEnumerable:
Queue<string> queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
queue.Enqueue("third");
queue.Enqueue("fourth");
// Builds a new queue. Items are now alphabetically ordered
Queue<string> orderedQueue = new Queue<string>(queue.OrderBy(z => z));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10272 次 |
| 最近记录: |