Skip to content

Commit 396da37

Browse files
authored
Merge pull request #488 from DenisPimenov/compact-list-contains
Add Contains and IndexOf methods for consistency with System.Collections.Generic.List<>
2 parents a2646dc + 433f434 commit 396da37

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

rd-net/Lifetimes/Collections/CompactList.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,27 @@ public void Clear()
6969
myMultipleValues = null;
7070
}
7171

72+
public bool Contains(T item, IEqualityComparer<T?> comparer)
73+
{
74+
return IndexOf(item, comparer) >= 0;
75+
}
76+
77+
public int IndexOf(T item, IEqualityComparer<T?> comparer)
78+
{
79+
switch (Count)
80+
{
81+
case 0: return -1;
82+
case 1: return comparer.Equals(mySingleValue, item) ? 0 : -1;
83+
default:
84+
Assertion.AssertNotNull(myMultipleValues);
85+
for (var i = 0; i < myMultipleValues.Count; i++)
86+
{
87+
if (comparer.Equals(myMultipleValues[i], item)) return i;
88+
}
89+
return -1;
90+
}
91+
}
92+
7293
public int LastIndexOf(T item, IEqualityComparer<T?> comparer)
7394
{
7495
switch (Count)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
using System.Collections.Generic;
2+
using JetBrains.Collections;
3+
using NUnit.Framework;
4+
5+
namespace Test.Lifetimes.Collections
6+
{
7+
[TestFixture]
8+
public class CompactListTest
9+
{
10+
[TestCase(new int[0], 1, false)]
11+
[TestCase(new[] { 1 }, 1, true)]
12+
[TestCase(new[] { 1 }, 2, false)]
13+
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, true)]
14+
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, false)]
15+
public void TestContains(int[] values, int value, bool expected)
16+
{
17+
var compactList = new CompactList<int>();
18+
for (int i = 0; i < values.Length; i++)
19+
{
20+
compactList.Add(values[i]);
21+
}
22+
23+
Assert.AreEqual(compactList.Contains(value, EqualityComparer<int>.Default), expected);
24+
}
25+
26+
[TestCase(new int[0], 1, -1)]
27+
[TestCase(new[] { 1 }, 1, 0)]
28+
[TestCase(new[] { 1 }, 2, -1)]
29+
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, 4)]
30+
[TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, -1)]
31+
public void TestIndexOf(int[] values, int value, int expectedIndex)
32+
{
33+
var compactList = new CompactList<int>();
34+
for (int i = 0; i < values.Length; i++)
35+
{
36+
compactList.Add(values[i]);
37+
}
38+
39+
Assert.AreEqual(compactList.IndexOf(value, EqualityComparer<int>.Default), expectedIndex);
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)