diff --git a/collection.go b/collection.go index 6975e92..ab6e9df 100644 --- a/collection.go +++ b/collection.go @@ -21,6 +21,19 @@ func (receiver *Collection[T]) Add(item ...T) { } } +// AddIfNotExists 如果元素不存在,则添加元素 +func (receiver *Collection[T]) AddIfNotExists(item T) { + receiver.lock.Lock() + defer receiver.lock.Unlock() + + for _, t := range *receiver.source { + if parse.IsEqual(t, item) { + return + } + } + *receiver.source = append(*receiver.source, item) +} + // AddRange 添加元素 func (receiver *Collection[T]) AddRange(lst Enumerable[T]) { if lst.Count() > 0 { diff --git a/test/collection_test.go b/test/collection_test.go index 28802d5..32aedcd 100644 --- a/test/collection_test.go +++ b/test/collection_test.go @@ -23,6 +23,15 @@ func Test_collection_Add(t *testing.T) { assert.Equal(t, 3, lst.Index(2)) } +func Test_collection_AddIfNotExists(t *testing.T) { + lst := collections.NewList[int](1, 2) + lst.AddIfNotExists(1) + lst.AddIfNotExists(2) + lst.AddIfNotExists(3) + assert.Equal(t, 3, lst.Count()) + assert.Equal(t, 3, lst.Index(2)) +} + func Test_collection_AddRange(t *testing.T) { lst := collections.NewList[int]() lst2 := collections.NewList[int](1, 2, 3)