【问题标题】:How to add values to an HashSet based on its content without allocating a new HashSet如何在不分配新 HashSet 的情况下根据其内容向 HashSet 添加值
【发布时间】:2020-05-14 14:20:12
【问题描述】:

我正在尝试根据 HashSet<string> 的内容向其添加值。

我希望代码看起来像这样:

public static void AddModifiedValues(HashSet<string> properties)
{
    if (properties is null)
    {
        return;
    }

    foreach (var element in properties)
    {
        result.Add(element + "id");
    }
}

这里的问题是,当我修改我正在迭代的集合时,我显然遇到了一个异常。

当前代码最终看起来像这样:

//different signature
public static HashSet<string> AddModifiedValues(HashSet<string> properties)
{
    //allocation
    var result = new HashSet<string>();
    if (properties is null)
    {
        return result;
    }

    foreach (var element in properties)
    {
        result.Add(element);
        result.Add(element + "id");
    }
    return result;
}

有没有办法在不分配新 HashSet 的情况下完成我正在寻找的事情?

【问题讨论】:

    标签: c# collections hashset


    【解决方案1】:

    很遗憾,您不能使用 Hashset 类型来做到这一点。

    其中一个原因是您无法跟踪集合(在本例中为 set)中旧值的结束位置,因为每次插入 hashet 都会在内部产生副作用。

    但是使用 List 是可能的。

    var properties = new List<string>()
    {
      "test1",
      "test2"
    };
    
    var length = properties.Count;
    
    for(var i = 0 ; i < length ; i++) {
      properties.Add(properties[i] + "id");
    }
    

    --编辑

    看来我错了,HashSet doesnt sort collection after inserting 所以你可以做的是使用ElementAt 来访问元素。

    var properties = new HashSet<string>()
    {
      "test1",
      "test2"
    };
    
    var length = properties.Count;
    
    for(var i = 0 ; i < length ; i++) {
      properties.Add(properties.ElementAt(i) + "id");
    }
    

    【讨论】:

    • 或者properties.Add(properties.ElementAt(i) + "id");使用原版HashSet
    • 更新了答案。谢谢!
    • 如果我错了,请纠正我,但ElementAt 是一种 LINQ 扩展方法,而不是类中的方法,所以我怀疑您使用此方法的编辑版本为 O(n²),当然,我也尽量避免。
    • 是的,ElementAt 方法将是 O(n^2),因为每次它会在内部执行 GetEnumerator()MoveNext() 直到索引与递增的迭代器匹配
    猜你喜欢
    • 2022-12-05
    • 2015-12-23
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多