aboutsummaryrefslogtreecommitdiff
path: root/src/Jellyfin.Extensions/EnumerableExtensions.cs
blob: 3eb9da01f2fe0608229be5eb39a9232aaf2041fc (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System;
using System.Collections.Generic;
using System.Linq;

namespace Jellyfin.Extensions;

/// <summary>
/// Static extensions for the <see cref="IEnumerable{T}"/> interface.
/// </summary>
public static class EnumerableExtensions
{
    /// <summary>
    /// Determines whether the value is contained in the source collection.
    /// </summary>
    /// <param name="source">An instance of the <see cref="IEnumerable{String}"/> interface.</param>
    /// <param name="value">The value to look for in the collection.</param>
    /// <param name="stringComparison">The string comparison.</param>
    /// <returns>A value indicating whether the value is contained in the collection.</returns>
    /// <exception cref="ArgumentNullException">The source is null.</exception>
    public static bool Contains(this IEnumerable<string> source, ReadOnlySpan<char> value, StringComparison stringComparison)
    {
        ArgumentNullException.ThrowIfNull(source);

        if (source is IList<string> list)
        {
            int len = list.Count;
            for (int i = 0; i < len; i++)
            {
                if (value.Equals(list[i], stringComparison))
                {
                    return true;
                }
            }

            return false;
        }

        foreach (string element in source)
        {
            if (value.Equals(element, stringComparison))
            {
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// Gets an IEnumerable from a single item.
    /// </summary>
    /// <param name="item">The item to return.</param>
    /// <typeparam name="T">The type of item.</typeparam>
    /// <returns>The IEnumerable{T}.</returns>
    public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item)
    {
        yield return item;
    }

    /// <summary>
    /// Gets an IEnumerable consisting of all flags of an enum.
    /// </summary>
    /// <param name="flags">The flags enum.</param>
    /// <typeparam name="T">The type of item.</typeparam>
    /// <returns>The IEnumerable{Enum}.</returns>
    public static IEnumerable<T> GetUniqueFlags<T>(this T flags)
        where T : Enum
    {
        foreach (Enum value in Enum.GetValues(flags.GetType()))
        {
            if (flags.HasFlag(value))
            {
                yield return (T)value;
            }
        }
    }
}