简体   繁体   English

在列表中获得唯一索引?

[英]Getting a unique index in a list?

The short and simple version is this: I have a database. 简短的版本是这样的:我有一个数据库。 I have ac# list that I use to interact with that database. 我有一个与该数据库进行交互的ac#列表。 Program starts, dump the data into the list, program ends, save it back into the database. 程序启动,将数据转储到列表中,程序结束,将其保存回数据库中。

Here's my problem though: I need to make sure that one of my attributes in the list (id) is always unique when I create and remove list items. 不过,这是我的问题:创建和删除列表项时,我需要确保列表(id)中的属性之一始终是唯一的。 I was thinking maybe a list might have something similiar to a SQL auto-increment? 我在想也许列表可能与SQL自动增量类似? Or perhaps just a numerical index of which item is in which location? 还是仅仅是哪个位置在哪个位置的数字索引?

AddedDependents.Add(new Dependent
                   {
                       IsSpouse = isSpouse,
                       Id = /*unique id/*
                   });

How about generating a Guid ? 生成Guid怎么样?

Eg 例如

AddedDependents.Add(
    new Dependent
    {
        IsSpouse = isSpouse,
        Id = Guid.NewGuid().ToString("N")
     });

Thus implies that your "Id" is a string, I could not read from your question whether this is possible or not. 因此暗示您的“ Id”是一个字符串,我无法从您的问题中读取这是否可能。

Alternatively, do no make it a string, but let it be a Guid type, like: 或者,不要将其设置为字符串,而应将其设置为Guid类型,例如:

AddedDependents.Add(
    new Dependent
    {
        IsSpouse = isSpouse,
        Id = Guid.NewGuid()
     });

You could just use the index of the list: 您可以只使用列表的索引:

AddedDependents.Add(new Dependent
               {
                   IsSpouse = isSpouse,
                   Id = AddedDependents.Count
               });

Then the Dependent Id and list index are the same so it becomes trivial to get that Dependent from the list. 然后, Dependent Id和列表索引相同,因此从列表中获取该Dependent变得微不足道。

As mentioned in the comments, if you are likely to delete elements from this list then you can't just get the dependent via the Id, like AddedDependents[dependent.Id] but instead would need to iterate through the list: 如评论中所述,如果您可能要从此列表中删除元素,那么您不仅可以通过Id获取依赖项,例如AddedDependents[dependent.Id] ,还需要遍历该列表:

AddedDependents.Where(d => d.Id == dependent.Id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM