From 26c7c088994fd15d73884e0c35c332a54ac0edcd Mon Sep 17 00:00:00 2001 From: IO Date: Wed, 3 Jul 2024 11:46:33 +0200 Subject: [PATCH] Add IndexOf, ReplaceElementAt and Resize List methods (#42) --- .../SimpleTypes/ListExpressionParser.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs b/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs index e9c638891..0c50eea22 100644 --- a/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs +++ b/source/ContractConfigurator/ExpressionParser/Parsers/SimpleTypes/ListExpressionParser.cs @@ -39,6 +39,7 @@ public static void RegisterMethods() RegisterMethod(new Method, int, T>("ElementAt", (l, i) => l == null ? default(T) : l.ElementAtOrDefault(i))); RegisterMethod(new Method, T, bool>("Contains", (l, o) => l == null ? false : l.Contains(o))); + RegisterMethod(new Method, T, int>("IndexOf", (l, o) => l == null ? -1 : l.IndexOf(o))); RegisterMethod(new Method, int>("Count", l => l == null ? 0 : l.Count)); @@ -46,6 +47,8 @@ public static void RegisterMethods() RegisterMethod(new Method, T, List>("Add", (l, v) => { if (l == null) { l = new List(); } l.ToList().Add(v); return l; })); RegisterMethod(new Method, T, List>("Exclude", (l, v) => { if (l != null) { l = l.ToList(); l.Remove(v); } return l; })); RegisterMethod(new Method, List, List>("ExcludeAll", (l, l2) => { if (l != null) { l = l.ToList(); if (l2 != null) { l.RemoveAll(x => l2.Contains(x)); } } return l; })); + RegisterMethod(new Method, int, T, List>("ReplaceElementAt", ReplaceElementAt)); + RegisterMethod(new Method, int, List>("Resize", Resize)); RegisterMethod(new Method, T>("SelectUnique", SelectUnique, false)); } @@ -178,6 +181,29 @@ protected static T SelectUnique(List input) return values.Skip(r.Next(values.Count())).FirstOrDefault(); } + protected static List ReplaceElementAt(List 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 Resize(List list, int size) + { + var newList = new List(); + + 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() {