ImmutableList <T>检查并删除

时间:2019-07-07 20:31:08

标签: c# .net .net-core

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

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

这可能吗?

1 个答案:

答案 0 :(得分:4)

由于不存在现成的功能,因此简单的扩展方法可以满足您的需求。

    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;
}