Skip to content

Commit

Permalink
Add IndexOf, ReplaceElementAt and Resize List methods (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
IO5 authored Jul 3, 2024
1 parent 71273de commit 26c7c08
Showing 1 changed file with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,16 @@ public static void RegisterMethods()
RegisterMethod(new Method<List<T>, int, T>("ElementAt", (l, i) => l == null ? default(T) : l.ElementAtOrDefault(i)));

RegisterMethod(new Method<List<T>, T, bool>("Contains", (l, o) => l == null ? false : l.Contains(o)));
RegisterMethod(new Method<List<T>, T, int>("IndexOf", (l, o) => l == null ? -1 : l.IndexOf(o)));

RegisterMethod(new Method<List<T>, int>("Count", l => l == null ? 0 : l.Count));

RegisterMethod(new Method<List<T>, List<T>, List<T>>("Concat", Concat));
RegisterMethod(new Method<List<T>, T, List<T>>("Add", (l, v) => { if (l == null) { l = new List<T>(); } l.ToList().Add(v); return l; }));
RegisterMethod(new Method<List<T>, T, List<T>>("Exclude", (l, v) => { if (l != null) { l = l.ToList(); l.Remove(v); } return l; }));
RegisterMethod(new Method<List<T>, List<T>, List<T>>("ExcludeAll", (l, l2) => { if (l != null) { l = l.ToList(); if (l2 != null) { l.RemoveAll(x => l2.Contains(x)); } } return l; }));
RegisterMethod(new Method<List<T>, int, T, List<T>>("ReplaceElementAt", ReplaceElementAt));
RegisterMethod(new Method<List<T>, int, List<T>>("Resize", Resize));

RegisterMethod(new Method<List<T>, T>("SelectUnique", SelectUnique, false));
}
Expand Down Expand Up @@ -178,6 +181,29 @@ protected static T SelectUnique(List<T> input)
return values.Skip(r.Next(values.Count())).FirstOrDefault();
}

protected static List<T> ReplaceElementAt(List<T> list, int idx, T replacement)
{
if (list == null || idx < 0 || idx >= list.Count)
return list;

var newList = list.ToList();
newList[idx] = replacement;

return newList;
}

protected static List<T> Resize(List<T> list, int size)
{
var newList = new List<T>();

if (list != null && size > 0)
newList.AddRange(list.Take(size));

if (newList.Count < size)
newList.AddRange(Enumerable.Repeat(default(T), size - newList.Count));

return newList;
}

public ListExpressionParser()
{
Expand Down

0 comments on commit 26c7c08

Please sign in to comment.