字典或列表c#

use*_*527 3 c# math dictionary

我有一个奇怪的C#编程问题,有一组随机长度的数字组的数据检索.这些数字应该是唯一的,例如:

group[1]{1,2,15}; 
group[2]{3,4,7,33,22,100};
group[3]{11,12,9};

//now there is a routine that adds number to a group
// for the eample just imagine the active group looks like:
// group[active]=(10,5,0)
group[active].add(new_number);

//now if 100 where to be added to the active group
//then active group should be merged to group[2] 
//(as that one allready contained 100)
//And then as a result it would like

group[1]{1,2,15}; 
group[2]{3,4,7,33,22,100,10,5,0};  //10 5 0 added to group[2]
group[3]{11,12,9};

// 100 wasnt added to group[2] since it was allready in there.
Run Code Online (Sandbox Code Playgroud)

如果要添加的号码在前一组中已全部就绪使用(非唯一).然后我应该将活动组中的所有数字合并到前一组,所以我不会得到双数.因此,在上面的示例中,如果将100号添加到活动组.然后group[active] 应该合并到所有数字group[2] 然后group[active]应该开始清洁新鲜没有项目.而且因为100已经在group[2]其中,所以不应该加倍.

我不完全确定如何以适当的方式处理这个问题.

这里的一个重要标准是它必须快速工作.我将有大约30个组(上限未知可能是2000或更多),它们的长度平均包含5个整数,但可能更长或只有1个数字

我觉得我在这里重新发明轮子.

  • 我想知道这个问题是如何被调用的.(它是通过名称,某些排序,还是分组数学问题)?,有了名称,我可能会找到一些与此类问题相关的文章.

  • 但也许它确实是新事物,那么你会推荐我什么?我应该使用列表列表还是列表字典..还是其他什么?以某种方式检查数字是否已经存在应该快速完成.

更新我现在正在思考这条路径,不确定它是否最好 而不是单个数字我现在使用结构,它不是写在原始问题中,因为我害怕,解释这将使它太复杂

struct data{int ID; int additionalNumber}

Dictionary <int,List<data>> group =new Dictionary<int, List<data>>(); 
Run Code Online (Sandbox Code Playgroud)

更新2 我可以在这里不使用结构,查找列表可以将其他数据连接到正确的索引.所以这又使它更接近原始描述.

在旁注上给出了很好的答案,到目前为止我还不知道在我的情况下什么对我最有用.

关于选定答案的注释 这里给出了几个答案,我选择了纯字典解决方案.就像在类似问题场景中的人们的注意事项一样,我仍然建议进行测试,也许其他人可以更好地为您工作.它只是在我的情况下目前它工作得最好,代码也很短,我喜欢,字典还为我未来的编码添加了其他方便的选项.

Sel*_*enç 5

我会继续Dictionary<int, HashSet<int>>,因为你想避免重复,并想要一个快速的方法来检查给定的数字是否已经存在:

用法示例:

var groups = new Dictionary<int, HashSet<int>>();

// populate the groups
groups[1] = new HashSet<int>(new[] { 1,2,15 });
groups[2] = new HashSet<int>(new[] { 3,4,7,33,22,100 });

int number = 5;
int groupId = 4;

bool numberExists = groups.Values.Any(x => x.Contains(number));

// if there is already a group that contains the number
// merge it with the current group and add the new number
if (numberExists)
{
     var group = groups.First(kvp => kvp.Value.Contains(number));
     groups[group.Key].UnionWith(groups[groupId]);
     groups[groupId] = new HashSet<int>();
}
// otherwise just add the new number
else
{
    groups[groupId].Add(number);
}
Run Code Online (Sandbox Code Playgroud)