我有一个System.Collections.Immutable.ImmutableList<T>,我想检查其中是否有物品,然后一步就将其删除。像这样:

var newList = oldList.Remove(item, out bool found);


这可能吗?

最佳答案

由于该功能并非开箱即用,因此简单的扩展方法可以满足您的需求。

    public static ImmutableList<T> Remove<T>(this ImmutableList<T> immutableList, T item, out bool found)
    {
        found = false;
        if (immutableList.Contains(item))
        {
            found = true;
            return immutableList.Remove(item);
        }
        return immutableList;
    }


你也可以

public static ImmutableList<T> Remove<T>(this ImmutableList<T> immutableList, T item, out bool found)
{
    var oldCount = immutableList.Count;
    var results = immutableList.Remove(item);
    found = oldCount > results.Count;
    return results;
}


但是,正如评论中提到的那样,这两种方法都不是那么有效。一个适当有效的模型可能需要是ImmutableList<T>的自定义实现,而不是像这样的扩展方法。

根据Slai的建议,这可能会更有效:

public static ImmutableList<T> Remove<T>(this ImmutableList<T> immutableList, T item, out bool found)
{
    found = false;
    var possibleLocation = immutableList.IndexOf(item);
    if (possibleLocation < 0)
    {
        return immutableList;
    }
    immutableList.RemoveAt(possibleLocation);
    found = true;
    return immutableList;
}

10-01 23:12