简体   繁体   English

用整数在C#中增加名称

[英]increasing names in C# with integers

I need to get an object and check if it already exists. 我需要获取一个对象并检查它是否已经存在。

In case it does, I want to add a number, or increase the number in its name. 如果确实如此,我想添加一个数字或增加其名称中的数字。 For example if I have the object "a" and it exists, I need to add a 1 so it's called a1. 例如,如果我有对象“ a”并且它存在,则需要添加一个1,因此称为a1。 In case a1 exists, a2, etc. 如果a1存在,则a2等。

How could I perform this? 我该如何执行呢?

My code: 我的代码:

if (e.TreeNode.Tag is Variant)
{
    if (variantExists(e.TreeNode.Text))
    {
        Random r = new Random();
        int randomNumber = r.Next(0, 99);
        e.TreeNode.Text = e.TreeNode.Text + randomNumber;
        //e.TreeNode.Remove(); 
        return;
    }
}

Can you change the TreeNode class? 您可以更改TreeNode类吗? I would add properties for Label (Name without Index) and Index and make the Name property read only, ie 我将为Label(没有索引的名称)和Index添加属性,并使Name属性为只读,即

class TreeNode
{
    public int Index {get;set;}
    public string Label {get;set;}

    public string Name 
    {
        get { return Index == 0 ? Label : Label + Index; }
    }
}

In your code you just need to set the Index property to the value you need and dont worry about the whole string parsing stuff 在您的代码中,您只需要将Index属性设置为所需的值,而不必担心整个字符串解析的问题

string name = "SomeName";

string tempName = name;
int n = 0;

while (DoesNameExist(tempName))
{
    n++;
    tempName = name + n;
}

name = tempName;

This gets ineffecient for large numbers of the same object, but that shouldn't happen right? 对于大量相同的对象,这变得效率低下,但这不应该对吗?

The problem with doing it the other way around, and stripping off trailing numbers to find the "original" name is that the original name may genuinely have numbers on it. 反之,这样做并去除尾随数字以找到“原始”名称的问题是,原始名称可能确实带有数字。

Eg. 例如。 You say you add: 您说要添加:

SomeName
SomeName99
SomeName
SomeName99

The above code will give you 上面的代码会给你

SomeName
SomeName1
SomeName99
SomeName991

Something along the lines of this could work: 可以遵循以下方法进行工作:

var existingItems = new HashSet<string>();
var items = new List<string>{"a", "b", "a"};
foreach (var item in items)
{
    var tempItem = item;
    var i = 1;
    while (!existingItems.Add(tempItem))
        tempItem = tempItem + i++;
}

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

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