Skip to content

Commit

Permalink
Consolidate structural differences in "*Like" types
Browse files Browse the repository at this point in the history
  • Loading branch information
atifaziz authored Jan 28, 2023
1 parent d6953fc commit a610d3a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 13 deletions.
12 changes: 12 additions & 0 deletions MoreLinq/CollectionLike.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,16 @@ public CollectionLike(IReadOnlyCollection<T> collection)
public IEnumerator<T> GetEnumerator() =>
_rw?.GetEnumerator() ?? _ro?.GetEnumerator() ?? Enumerable.Empty<T>().GetEnumerator();
}

static class CollectionLike
{
public static CollectionLike<T>? TryAsCollectionLike<T>(this IEnumerable<T> source) =>
source switch
{
null => throw new ArgumentNullException(nameof(source)),
ICollection<T> collection => new(collection),
IReadOnlyCollection<T> collection => new(collection),
_ => null
};
}
}
6 changes: 2 additions & 4 deletions MoreLinq/ListLike.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,6 @@ public ListLike(IReadOnlyList<T> list)
static class ListLike
{
public static ListLike<T> AsListLike<T>(this List<T> list) => new((IList<T>)list);
public static ListLike<T> AsListLike<T>(this IList<T> list) => new(list);
public static ListLike<T> AsListLike<T>(this IReadOnlyList<T> list) => new(list);

public static ListLike<T> ToListLike<T>(this IEnumerable<T> source)
=> source.TryAsListLike() ?? source.ToList().AsListLike();
Expand All @@ -64,8 +62,8 @@ public static ListLike<T> ToListLike<T>(this IEnumerable<T> source)
source switch
{
null => throw new ArgumentNullException(nameof(source)),
IList<T> list => list.AsListLike(),
IReadOnlyList<T> list => list.AsListLike(),
IList<T> list => new(list),
IReadOnlyList<T> list => new(list),
_ => null
};
}
Expand Down
9 changes: 0 additions & 9 deletions MoreLinq/MoreEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,6 @@ namespace MoreLinq

public static partial class MoreEnumerable
{
internal static CollectionLike<T>? TryAsCollectionLike<T>(this IEnumerable<T> source) =>
source switch
{
null => throw new ArgumentNullException(nameof(source)),
ICollection<T> collection => new CollectionLike<T>(collection),
IReadOnlyCollection<T> collection => new CollectionLike<T>(collection),
_ => null
};

static int CountUpTo<T>(this IEnumerable<T> source, int max)
{
if (source == null) throw new ArgumentNullException(nameof(source));
Expand Down

0 comments on commit a610d3a

Please sign in to comment.