I'm currently working on a project that I had to create basically a running queue of items. My thought was to do this by a list, but surprisingly there weren't any methods to remove the first sequence or last sequence of items in a list that I found. I wrote the following class with extension methods for List<T>
:
using System;
using System.Collections.Generic;
using System.Linq;
namespace Extensions
{
public static class ExtensionClass
{
public static bool TrimFirst<T>(this List<T> list, int maxCount)
{
try
{
if (list.Count <= maxCount)
{
throw new InvalidOperationException
("Items in list <= maxCount, unable to trim list.");
}
while (list.Count > maxCount)
{
T first = list.First<T>();
list.Remove(first);
}
return true;
}
catch
{
return false;
}
}
public static bool TrimLast<T>(this List<T> list, int maxCount)
{
try
{
if (list.Count <= maxCount)
{
throw new InvalidOperationException
("Items in list <= maxCount, unable to trim list.");
}
while (list.Count > maxCount)
{
T last = list.Last<T>();
list.Remove(last);
}
return true;
}
catch
{
return false;
}
}
public static bool ItemExists<T>(this List<T> list, T item)
{
foreach (T listItem in list)
{
if (item.ToString() == listItem.ToString())
{
return true;
}
}
return false;
}
}
}
This seems something that I will likely use in the future, so I would like to optimize it and make it as flexible as possible. Does anyone have any suggestions? For reference, the try/catch/exception are in case I need to modify the code to deal with that in the future, although I was not quite sure about the way that I wrote that part of the code. Anyone that needs this function, feel free to use this code!
I have also added the ItemExists()
method since I hate the Any()
and Exists()
methods' use of a predicate. As far as I know, this method processes the items by enumeration, just at the built-in methods do, except they possibly use a Parallel.ForEach
loop. Any suggestions for optimizing this method?
LinkedList<>
which specifically provides functions for adding to or removing from both ends. \$\endgroup\$