我正在尝试找到一种有效的方法来将唯一数值添加到列表中。目前,我正在使用Dictionary<int,int>
对象。第一个值是生成的数字;只要它的生成可以在相同的情况下重复,它并不重要。第二项是原件。所以,我会这样:
Dictionary<int,int> orderedList = new Dictionary<int,int>(MaxNoOfTimes);
for (i = 0; i<MaxNoOfTimes, i++)
{
int j = getNewValue();
retry:
try
{
orderedList.Add(j,i);
}
catch (ArgumentException ex)
{
goto retry;
}
虽然这很有效,但它看起来很不合理,我认为由于异常处理它很慢。 MaxNoOftimes的值可以达到几千(实际上没有实际限制,但是超过1000甚至很少)。有更快的方法吗?在我完成将值添加到orderedList之后,我从orderedList创建了一个SortList。
答案 0 :(得分:2)
怎么样:
for (i = 0; i<MaxNoOfTimes, i++)
{
int j = getNewValue();
while(orderedList.ContainsKey(j))
{
j = getNewValue();
}
orderedList.Add(j, i);
}
答案 1 :(得分:0)
怎么样:
Hashset<int> orderedSet = new Hashset<int>();
while(orderedSet.Count < maxNoTimes)
{
int j = getNewValue();
orderedSet.Add(j);
}
因为,你说你需要每个值的序数,那么这可能是你在订购时想要的:
var orderedDictionary = orderedSet.ToDictionary(i => orderedSet.ToList().IndexOf(i), i => i).OrderBy(i => i.Value);