From 433f434320b6522ca5ce42c8975e7089f369b610 Mon Sep 17 00:00:00 2001 From: denispimenov Date: Mon, 29 Jul 2024 18:24:39 +0300 Subject: [PATCH] Add Contains and IndexOf methods for consistency with System.Collections.Generic.List<> --- rd-net/Lifetimes/Collections/CompactList.cs | 21 ++++++++++ .../Collections/CompactListTest.cs | 42 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 rd-net/Test.Lifetimes/Collections/CompactListTest.cs diff --git a/rd-net/Lifetimes/Collections/CompactList.cs b/rd-net/Lifetimes/Collections/CompactList.cs index 920b9af68..d6bd21d3c 100644 --- a/rd-net/Lifetimes/Collections/CompactList.cs +++ b/rd-net/Lifetimes/Collections/CompactList.cs @@ -69,6 +69,27 @@ public void Clear() myMultipleValues = null; } + public bool Contains(T item, IEqualityComparer comparer) + { + return IndexOf(item, comparer) >= 0; + } + + public int IndexOf(T item, IEqualityComparer comparer) + { + switch (Count) + { + case 0: return -1; + case 1: return comparer.Equals(mySingleValue, item) ? 0 : -1; + default: + Assertion.AssertNotNull(myMultipleValues); + for (var i = 0; i < myMultipleValues.Count; i++) + { + if (comparer.Equals(myMultipleValues[i], item)) return i; + } + return -1; + } + } + public int LastIndexOf(T item, IEqualityComparer comparer) { switch (Count) diff --git a/rd-net/Test.Lifetimes/Collections/CompactListTest.cs b/rd-net/Test.Lifetimes/Collections/CompactListTest.cs new file mode 100644 index 000000000..eb616628f --- /dev/null +++ b/rd-net/Test.Lifetimes/Collections/CompactListTest.cs @@ -0,0 +1,42 @@ +using System.Collections.Generic; +using JetBrains.Collections; +using NUnit.Framework; + +namespace Test.Lifetimes.Collections +{ + [TestFixture] + public class CompactListTest + { + [TestCase(new int[0], 1, false)] + [TestCase(new[] { 1 }, 1, true)] + [TestCase(new[] { 1 }, 2, false)] + [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, true)] + [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, false)] + public void TestContains(int[] values, int value, bool expected) + { + var compactList = new CompactList(); + for (int i = 0; i < values.Length; i++) + { + compactList.Add(values[i]); + } + + Assert.AreEqual(compactList.Contains(value, EqualityComparer.Default), expected); + } + + [TestCase(new int[0], 1, -1)] + [TestCase(new[] { 1 }, 1, 0)] + [TestCase(new[] { 1 }, 2, -1)] + [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, 4)] + [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, -1)] + public void TestIndexOf(int[] values, int value, int expectedIndex) + { + var compactList = new CompactList(); + for (int i = 0; i < values.Length; i++) + { + compactList.Add(values[i]); + } + + Assert.AreEqual(compactList.IndexOf(value, EqualityComparer.Default), expectedIndex); + } + } +} \ No newline at end of file