Skip to content

Commit cd2a176

Browse files
author
Kapil Borle
committed
Implement extension method get max array element
1 parent bd94337 commit cd2a176

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/PowerShellEditorServices/Utility/Extensions.cs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
//
55

66
using System;
7+
using System.Linq;
8+
using System.Collections.Generic;
9+
using System.Management.Automation.Language;
710

811
namespace Microsoft.PowerShell.EditorServices.Utility
912
{
@@ -30,5 +33,34 @@ public static string SafeToString(this object obj)
3033

3134
return str;
3235
}
36+
37+
public static T MaxElement<T>(this IEnumerable<T> elements, Func<T,T,int> comparer) where T:class
38+
{
39+
if (elements == null)
40+
{
41+
throw new ArgumentNullException(nameof(elements));
42+
}
43+
44+
if (comparer == null)
45+
{
46+
throw new ArgumentNullException(nameof(comparer));
47+
}
48+
49+
if (!elements.Any())
50+
{
51+
return null;
52+
}
53+
54+
var maxElement = elements.First();
55+
foreach(var element in elements.Skip(1))
56+
{
57+
if (element != null && comparer(element, maxElement) > 0)
58+
{
59+
maxElement = element;
60+
}
61+
}
62+
63+
return maxElement;
64+
}
3365
}
3466
}

0 commit comments

Comments
 (0)