Answered by:
compose a generic a method

Question
-
hi
public static void RemoveOutOfRangeCircles(ref List<Simple2DCircle> list, float min, float max) { for (int i = 0; i < list.Count; i++) { if (list[i].Radius.IsNotBetween(min, max)) { list.RemoveAt(i); i--; } } } public static void RemoveOutOfRangeLines(ref List<Simple2DLine> list, float min, float max) { for (int i = 0; i < list.Count; i++) { if (list[i].Length.IsNotBetween(min, max)) { list.RemoveAt(i); i--; } } }
is there a way to make a generic method instead of those two mehtods.
Monday, February 24, 2020 12:10 PM
Answers
-
Hi,
You could do it like this :
public static void RemoveOutOfRange<T>(ref List<T> list, Predicate<T> predicate) { for (int i = 0; i < list.Count; i++) { if (predicate(list[i])) { list.RemoveAt(i); i--; } } } //call like this RemoveOutOfRange(ref circles, item => item.Radius.IsNotBetween(10, 100)); RemoveOutOfRange(ref lines, item => item.Length.IsNotBetween(10,100));
but there is allready a function for this.
circles.RemoveAll(item => item.Radius.IsNotBetween(10, 100)); lines.RemoveAll(item => item.Length.IsNotBetween(10, 100));
Hope this helps,
Here to learn and share. Please tell if an answer was helpful or not at all. This adds value to the answers and enables me to learn more.
About meMonday, February 24, 2020 12:47 PM
All replies
-
Hi,
You could do it like this :
public static void RemoveOutOfRange<T>(ref List<T> list, Predicate<T> predicate) { for (int i = 0; i < list.Count; i++) { if (predicate(list[i])) { list.RemoveAt(i); i--; } } } //call like this RemoveOutOfRange(ref circles, item => item.Radius.IsNotBetween(10, 100)); RemoveOutOfRange(ref lines, item => item.Length.IsNotBetween(10,100));
but there is allready a function for this.
circles.RemoveAll(item => item.Radius.IsNotBetween(10, 100)); lines.RemoveAll(item => item.Length.IsNotBetween(10, 100));
Hope this helps,
Here to learn and share. Please tell if an answer was helpful or not at all. This adds value to the answers and enables me to learn more.
About meMonday, February 24, 2020 12:47 PM -
//The bellow code is in linq public static void RemoveOutOfRangeCircles(ref List<Simple2DCircle> list, float min, float max) { var removelist = from r in list where (!(r.Radius >= min && r.Radius <= max) || !(r.Length >= min && r.Length <= max) ) select r; forEach(var v in removelist) { list.Remove(v); } } or //The bellow code is in lambda public static void RemoveOutOfRangeCircles(ref List<Simple2DCircle> list, float min, float max) { list.RemoveAll(r => !(r.Radius >= min && r.Radius <= max) || !(r.Length >= min && r.Length <= max) ) }
Monday, February 24, 2020 1:16 PM