Adding list extension methods for adding items to a sorted list

This commit is contained in:
Chris Cameron
2017-07-21 09:52:46 -04:00
parent 71b3c5ad2a
commit 442bd20759
3 changed files with 123 additions and 0 deletions

View File

@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using ICD.Common.Properties;
namespace ICD.Common.Utils.Extensions
{
/// <summary>
/// Extension methods for working with Lists.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Adds the item into a sorted list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="item"></param>
[PublicAPI]
public static void AddSorted<T>(this List<T> extends, T item)
{
if (extends == null)
throw new ArgumentNullException("extends");
extends.AddSorted(item, Comparer<T>.Default);
}
/// <summary>
/// Adds the item into a sorted list.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="extends"></param>
/// <param name="item"></param>
/// <param name="comparer"></param>
[PublicAPI]
public static void AddSorted<T>(this List<T> extends, T item, IComparer<T> comparer)
{
if (extends == null)
throw new ArgumentNullException("extends");
if (comparer == null)
throw new ArgumentNullException("comparer");
if (extends.Count == 0)
{
extends.Add(item);
return;
}
if (comparer.Compare(extends[extends.Count - 1], item) <= 0)
{
extends.Add(item);
return;
}
if (comparer.Compare(extends[0], item) >= 0)
{
extends.Insert(0, item);
return;
}
int index = extends.BinarySearch(item);
if (index < 0)
index = ~index;
extends.Insert(index, item);
}
}
}

View File

@@ -85,6 +85,7 @@
<Compile Include="EventArguments\XmlRecursionEventArgs.cs" />
<None Include="ObfuscationSettings.cs" />
<Compile Include="Extensions\ByteExtensions.cs" />
<Compile Include="Extensions\ListExtensions.cs" />
<Compile Include="Properties\Annotations.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Services\Logging\ILoggerService.cs" />