如果我需要控制项的位置并且需要能够序列化集合,那么我应该使用什么集合



我需要一个集合,但我不确定该使用哪一个。我以前使用过List,但我也需要确定具体的位置。如果用户查看了一个项目A,我会将其广告到收藏中,如果他看到另一个项目B,我会在第一个项目的顶部添加该项目,以此类推,但这些项目的限制数量是3,所以我会删除第一个项目,我还需要能够对收藏进行序列化。我尝试过Dictionary,但我可以使用XmlSerializer,所以我尝试过使用Lst<KeyValue<gt>现在我正在尝试这样的数组。还查看了Queue,但我发现使用XmlSerializer也可能是一个问题。有什么建议我可以用什么收藏品吗?

class Program
{
static void Main(string[] args)
{
string[] myObjArray = new string[3] ;
if(myObjArray[0] == null)
{
myObjArray[0] = "article1";
Console.WriteLine(myObjArray[0]);
}
if (myObjArray[1] == null )
{
myObjArray[1] = "article2";
Console.WriteLine(myObjArray[1]);
}
if (myObjArray[2] == null)
{
myObjArray[2] = "article3";
Console.WriteLine(myObjArray[2]);
}
var input =  Console.ReadLine();
myObjArray[0] = input;
Console.WriteLine(myObjArray[0]);

}
}

您可以使用List<Item>Index作为位置和方法InsertDelete来实现您的目标。如果职位被封装在实体中,你可以创建管理它的方法。

因此,当你添加一个项目时,你会检查计数是否超过允许的数量,如果需要,则删除第一个。

[Serializable]
public class MyList
{
private readonly List<Item> Items = new List<Item>();
public int Count { get { return Items.Count; } }
public int MaxCount { get; set; } = 0;
public void Add(Item item)
{
if ( MaxCount > 0 && Items.Count >= MaxCount )
Items.RemoveAt(0);
Items.Add(item);
}
public void Insert(int index, Item item)
{
Items.Insert(index, item);
}
public int FindById(int id)
{
for ( int index = 0; index < Items.Count; index++ )
if ( Items[index].Id == id )
return index;
return - 1;
}
// Add all over new methods and wrapping methods needed
}

此代码使用0表示不考虑最大计数,但如果列表可能不接受项,则可以为此管理-1,因此0表示列表已关闭。

也许您可以使用可序列化的LinkedList,但您需要为XML:实现它

https://learn.microsoft.com/dotnet/api/system.collections.generic.linkedlist-1

如何对LinkedList进行Xml序列化?

因此,有了它,你可以像你写的那样轻松地管理项目:

  • 在两个单元格之间添加一个单元格
  • 在单元格之前添加单元格
  • 在单元格后添加单元格
  • 在开始处添加单元格
  • 在末尾添加一个单元格
  • 拆下第一个
  • 删除最后一个
  • 等等

因此,如果计数超过允许值,则可以添加自动删除第一个单元格。

我什么时候应该使用List与LinkedList

C#中的链接列表-tutorialspoint.com

链接列表-dotnetcademy.net

C#|链接列表类-geeksfoeks.org

C#中的链表实现-geeksfoeks.org

最新更新