aboutsummaryrefslogtreecommitdiffstats
path: root/examples/UserView/UserViewLib/UserList.cs
blob: acba9e98259ede4f65d72f341d4dd01b8498edc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/***************************************************************************************************
 Copyright (C) 2025 The Qt Company Ltd.
 SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
***************************************************************************************************/

using System.Collections;

namespace UserViewLib
{
    public interface IUserList : IEnumerable<User>
    {
        int Count { get; }
        void Add(User user, int index = -1);
        void RemoveAt(int index);
        int BinarySearch(User user, IComparer<User> comparer);
    }

    public class UserList : IUserList
    {
        private List<User> Users { get; set; } = [];

        public int Count => Users.Count;

        public void Add(User user, int index = -1)
        {
            if (user == null)
                return;
            if (index < 0 || index > Users.Count)
                index = Users.Count;
            Users.Insert(index, user);
        }

        public void RemoveAt(int index)
        {
            if (index < 0 || index >= Users.Count)
                return;
            Users.RemoveAt(index);
        }

        public int BinarySearch(User user, IComparer<User> comparer)
        {
            if (user == null)
                return ~Users.Count;
            return Users.BinarySearch(user, comparer);
        }

        public IEnumerator<User> GetEnumerator() => Users.ToList().GetEnumerator();
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}