forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOrderObjectBase.cs
More file actions
730 lines (631 loc) · 28.3 KB
/
Copy pathOrderObjectBase.cs
File metadata and controls
730 lines (631 loc) · 28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Management.Automation.Internal;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Definitions for hash table keys.
/// </summary>
internal static class SortObjectParameterDefinitionKeys
{
internal const string AscendingEntryKey = "ascending";
internal const string DescendingEntryKey = "descending";
}
/// <summary>
/// </summary>
internal sealed class SortObjectExpressionParameterDefinition : CommandParameterDefinition
{
protected override void SetEntries()
{
this.hashEntries.Add(new ExpressionEntryDefinition(false));
this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.AscendingEntryKey));
this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.DescendingEntryKey));
}
}
/// <summary>
/// </summary>
internal sealed class GroupObjectExpressionParameterDefinition : CommandParameterDefinition
{
protected override void SetEntries()
{
this.hashEntries.Add(new ExpressionEntryDefinition(true));
}
}
/// <summary>
/// Base Cmdlet for cmdlets which deal with raw objects.
/// </summary>
public class ObjectCmdletBase : PSCmdlet
{
#region Parameters
/// <summary>
/// </summary>
/// <value></value>
[Parameter]
[System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "The CultureNumber is only used if the property has been set with a hex string starting with 0x")]
public string Culture
{
get
{
return _cultureInfo?.ToString();
}
set
{
if (string.IsNullOrEmpty(value))
{
_cultureInfo = null;
return;
}
int cultureNumber;
string trimmedValue = value.Trim();
if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
{
if ((trimmedValue.Length > 2) &&
int.TryParse(trimmedValue.AsSpan(2), NumberStyles.AllowHexSpecifier,
CultureInfo.CurrentCulture, out cultureNumber))
{
_cultureInfo = new CultureInfo(cultureNumber);
return;
}
}
else if (int.TryParse(trimmedValue, NumberStyles.AllowThousands,
CultureInfo.CurrentCulture, out cultureNumber))
{
_cultureInfo = new CultureInfo(cultureNumber);
return;
}
_cultureInfo = new CultureInfo(value);
}
}
internal CultureInfo _cultureInfo = null;
/// <summary>
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter CaseSensitive
{
get { return _caseSensitive; }
set { _caseSensitive = value; }
}
private bool _caseSensitive;
#endregion Parameters
}
/// <summary>
/// Base Cmdlet for object cmdlets that deal with Grouping, Sorting and Comparison.
/// </summary>
public abstract class ObjectBase : ObjectCmdletBase
{
#region Parameters
/// <summary>
/// </summary>
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject { get; set; } = AutomationNull.Value;
/// <summary>
/// Gets or Sets the Properties that would be used for Grouping, Sorting and Comparison.
/// </summary>
[Parameter(Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public object[] Property { get; set; }
#endregion Parameters
}
/// <summary>
/// Base Cmdlet for object cmdlets that deal with Ordering and Comparison.
/// </summary>
public class OrderObjectBase : ObjectBase
{
#region Internal Properties
/// <summary>
/// Specifies sorting order.
/// </summary>
internal SwitchParameter DescendingOrder
{
get { return !_ascending; }
set { _ascending = !value; }
}
private bool _ascending = true;
internal List<PSObject> InputObjects { get; } = new List<PSObject>();
/// <summary>
/// CultureInfo converted from the Culture Cmdlet parameter.
/// </summary>
internal CultureInfo ConvertedCulture
{
get
{
return _cultureInfo;
}
}
#endregion Internal Properties
/// <summary>
/// Simply accumulates the incoming objects.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject != null && InputObject != AutomationNull.Value)
{
InputObjects.Add(InputObject);
}
}
}
internal sealed class OrderByProperty
{
#region Internal properties
/// <summary>
/// A logical matrix where each row is an input object and its property values specified by Properties.
/// </summary>
internal List<OrderByPropertyEntry> OrderMatrix { get; }
internal OrderByPropertyComparer Comparer { get; }
internal List<MshParameter> MshParameterList
{
get
{
return _mshParameterList;
}
}
#endregion Internal properties
#region Utils
// These are made static for Measure-Object's GroupBy parameter that measure the outputs of Group-Object
// However, Measure-Object differs from Group-Object and Sort-Object considerably that it should not
// be built on the same base class, i.e., this class. Moreover, Measure-Object's Property parameter is
// a string array and allows wildcard.
// Yes, the Cmdlet is needed. It's used to get the TerminatingErrorContext, WriteError and WriteDebug.
#region process PSPropertyExpression and MshParameter
private static void ProcessExpressionParameter(
List<PSObject> inputObjects,
PSCmdlet cmdlet,
object[] expr,
out List<MshParameter> mshParameterList)
{
mshParameterList = null;
TerminatingErrorContext invocationContext = new(cmdlet);
// compare-object and group-object use the same definition here
ParameterProcessor processor = cmdlet is SortObjectCommand ?
new ParameterProcessor(new SortObjectExpressionParameterDefinition()) :
new ParameterProcessor(new GroupObjectExpressionParameterDefinition());
if (expr == null && inputObjects != null && inputObjects.Count > 0)
{
expr = GetDefaultKeyPropertySet(inputObjects[0]);
}
if (expr != null)
{
List<MshParameter> unexpandedParameterList = processor.ProcessParameters(expr, invocationContext);
mshParameterList = ExpandExpressions(inputObjects, unexpandedParameterList);
}
// NOTE: if no parameters are passed, we will look at the default keys of the first
// incoming object
}
internal void ProcessExpressionParameter(
PSCmdlet cmdlet,
object[] expr)
{
TerminatingErrorContext invocationContext = new(cmdlet);
// compare-object and group-object use the same definition here
ParameterProcessor processor = cmdlet is SortObjectCommand ?
new ParameterProcessor(new SortObjectExpressionParameterDefinition()) :
new ParameterProcessor(new GroupObjectExpressionParameterDefinition());
if (expr != null)
{
if (_unexpandedParameterList == null)
{
_unexpandedParameterList = processor.ProcessParameters(expr, invocationContext);
foreach (MshParameter unexpandedParameter in _unexpandedParameterList)
{
PSPropertyExpression mshExpression = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings
{
_mshParameterList.Add(unexpandedParameter);
}
else
{
_unExpandedParametersWithWildCardPattern ??= new List<MshParameter>();
_unExpandedParametersWithWildCardPattern.Add(unexpandedParameter);
}
}
}
}
}
// Expand a list of (possibly wildcarded) expressions into resolved expressions that
// match property names on the incoming objects.
private static List<MshParameter> ExpandExpressions(List<PSObject> inputObjects, List<MshParameter> unexpandedParameterList)
{
List<MshParameter> expandedParameterList = new();
if (unexpandedParameterList != null)
{
foreach (MshParameter unexpandedParameter in unexpandedParameterList)
{
PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings
{
expandedParameterList.Add(unexpandedParameter);
}
else
{
SortedDictionary<string, PSPropertyExpression> expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase);
if (inputObjects != null)
{
foreach (object inputObject in inputObjects)
{
if (inputObject == null)
{
continue;
}
foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject)))
{
expandedPropertyNames[resolvedName.ToString()] = resolvedName;
}
}
}
foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values)
{
MshParameter expandedParameter = new();
expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone();
expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression;
expandedParameterList.Add(expandedParameter);
}
}
}
}
return expandedParameterList;
}
// Expand a list of (possibly wildcarded) expressions into resolved expressions that
// match property names on the incoming objects.
private static void ExpandExpressions(PSObject inputObject, List<MshParameter> UnexpandedParametersWithWildCardPattern, List<MshParameter> expandedParameterList)
{
if (UnexpandedParametersWithWildCardPattern != null)
{
foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern)
{
PSPropertyExpression ex = (PSPropertyExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey);
SortedDictionary<string, PSPropertyExpression> expandedPropertyNames = new(StringComparer.OrdinalIgnoreCase);
if (inputObject == null)
{
continue;
}
foreach (PSPropertyExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject)))
{
expandedPropertyNames[resolvedName.ToString()] = resolvedName;
}
foreach (PSPropertyExpression expandedExpression in expandedPropertyNames.Values)
{
MshParameter expandedParameter = new();
expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone();
expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression;
expandedParameterList.Add(expandedParameter);
}
}
}
}
internal static string[] GetDefaultKeyPropertySet(PSObject mshObj)
{
PSMemberSet standardNames = mshObj.PSStandardMembers;
if (standardNames == null)
{
return null;
}
if (standardNames.Members["DefaultKeyPropertySet"] is not PSPropertySet defaultKeys)
{
return null;
}
string[] props = new string[defaultKeys.ReferencedPropertyNames.Count];
defaultKeys.ReferencedPropertyNames.CopyTo(props, 0);
return props;
}
#endregion process PSPropertyExpression and MshParameter
internal static List<OrderByPropertyEntry> CreateOrderMatrix(
PSCmdlet cmdlet,
List<PSObject> inputObjects,
List<MshParameter> mshParameterList
)
{
List<OrderByPropertyEntry> orderMatrixToCreate = new();
for (int index = 0; index < inputObjects.Count; index++)
{
PSObject so = inputObjects[index];
if (so == null || so == AutomationNull.Value)
continue;
List<ErrorRecord> evaluationErrors = new();
List<string> propertyNotFoundMsgs = new();
OrderByPropertyEntry result =
OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs, originalIndex: index);
foreach (ErrorRecord err in evaluationErrors)
{
cmdlet.WriteError(err);
}
foreach (string debugMsg in propertyNotFoundMsgs)
{
cmdlet.WriteDebug(debugMsg);
}
orderMatrixToCreate.Add(result);
}
return orderMatrixToCreate;
}
private static bool isOrderEntryKeyDefined(object orderEntryKey)
{
return orderEntryKey != null && orderEntryKey != AutomationNull.Value;
}
private static OrderByPropertyComparer CreateComparer(
List<OrderByPropertyEntry> orderMatrix,
List<MshParameter> mshParameterList,
bool ascending,
CultureInfo cultureInfo,
bool caseSensitive)
{
if (orderMatrix == null || orderMatrix.Count == 0)
{
return null;
}
bool?[] ascendingOverrides = null;
if (mshParameterList != null && mshParameterList.Count != 0)
{
ascendingOverrides = new bool?[mshParameterList.Count];
for (int k = 0; k < ascendingOverrides.Length; k++)
{
object ascendingVal = mshParameterList[k].GetEntry(
SortObjectParameterDefinitionKeys.AscendingEntryKey);
object descendingVal = mshParameterList[k].GetEntry(
SortObjectParameterDefinitionKeys.DescendingEntryKey);
bool isAscendingDefined = isOrderEntryKeyDefined(ascendingVal);
bool isDescendingDefined = isOrderEntryKeyDefined(descendingVal);
if (!isAscendingDefined && !isDescendingDefined)
{
// if neither ascending nor descending is defined
ascendingOverrides[k] = null;
}
else if (isAscendingDefined && isDescendingDefined &&
(bool)ascendingVal == (bool)descendingVal)
{
// if both ascending and descending defined but their values conflict
// they are ignored.
ascendingOverrides[k] = null;
}
else if (isAscendingDefined)
{
ascendingOverrides[k] = (bool)ascendingVal;
}
else
{
ascendingOverrides[k] = !(bool)descendingVal;
}
}
}
OrderByPropertyComparer comparer =
OrderByPropertyComparer.CreateComparer(orderMatrix, ascending,
ascendingOverrides, cultureInfo, caseSensitive);
return comparer;
}
internal OrderByProperty(
PSCmdlet cmdlet,
List<PSObject> inputObjects,
object[] expr,
bool ascending,
CultureInfo cultureInfo,
bool caseSensitive
)
{
Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance");
ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList);
OrderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList);
Comparer = CreateComparer(OrderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive);
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderByProperty"/> class.
/// </summary>
internal OrderByProperty()
{
_mshParameterList = new List<MshParameter>();
OrderMatrix = new List<OrderByPropertyEntry>();
}
/// <summary>
/// Utility function used to create OrderByPropertyEntry for the supplied input object.
/// </summary>
/// <param name="cmdlet">PSCmdlet.</param>
/// <param name="inputObject">Input Object.</param>
/// <param name="isCaseSensitive">Indicates if the Property value comparisons need to be case sensitive or not.</param>
/// <param name="cultureInfo">Culture Info that needs to be used for comparison.</param>
/// <returns>OrderByPropertyEntry for the supplied InputObject.</returns>
internal OrderByPropertyEntry CreateOrderByPropertyEntry(
PSCmdlet cmdlet,
PSObject inputObject,
bool isCaseSensitive,
CultureInfo cultureInfo)
{
Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance");
if (_unExpandedParametersWithWildCardPattern != null)
{
ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList);
}
List<ErrorRecord> evaluationErrors = new();
List<string> propertyNotFoundMsgs = new();
OrderByPropertyEntry result =
OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo);
foreach (ErrorRecord err in evaluationErrors)
{
cmdlet.WriteError(err);
}
foreach (string debugMsg in propertyNotFoundMsgs)
{
cmdlet.WriteDebug(debugMsg);
}
return result;
}
#endregion Utils
// list of processed parameters obtained from the Expression array
private readonly List<MshParameter> _mshParameterList = null;
// list of unprocessed parameters obtained from the Expression array.
private List<MshParameter> _unexpandedParameterList = null;
// list of unprocessed parameters with wild card patterns.
private List<MshParameter> _unExpandedParametersWithWildCardPattern = null;
}
internal static class OrderByPropertyEntryEvaluationHelper
{
internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List<MshParameter> mshParameterList,
List<ErrorRecord> errors, List<string> propertyNotFoundMsgs, bool isCaseSensitive = false, CultureInfo cultureInfo = null, int originalIndex = -1)
{
Diagnostics.Assert(errors != null, "errors cannot be null!");
Diagnostics.Assert(propertyNotFoundMsgs != null, "propertyNotFoundMsgs cannot be null!");
OrderByPropertyEntry entry = new();
entry.inputObject = inputObject;
entry.originalIndex = originalIndex;
if (mshParameterList == null || mshParameterList.Count == 0)
{
// we do not have a property to evaluate, we sort on $_
entry.orderValues.Add(new ObjectCommandPropertyValue(inputObject, isCaseSensitive, cultureInfo));
entry.comparable = true;
return entry;
}
// we need to compute the properties
foreach (MshParameter p in mshParameterList)
{
string propertyNotFoundMsg = null;
EvaluateSortingExpression(p, inputObject, entry.orderValues, errors, out propertyNotFoundMsg, ref entry.comparable);
if (!string.IsNullOrEmpty(propertyNotFoundMsg))
{
propertyNotFoundMsgs.Add(propertyNotFoundMsg);
}
}
return entry;
}
private static void EvaluateSortingExpression(
MshParameter p,
PSObject inputObject,
List<ObjectCommandPropertyValue> orderValues,
List<ErrorRecord> errors,
out string propertyNotFoundMsg,
ref bool comparable)
{
// NOTE: we assume globbing was not allowed in input
PSPropertyExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as PSPropertyExpression;
// get the values, but do not expand aliases
List<PSPropertyExpressionResult> expressionResults = ex.GetValues(inputObject, false, true);
if (expressionResults.Count == 0)
{
// we did not get any result out of the expression:
// we enter a null as a place holder
orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty);
propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString());
return;
}
propertyNotFoundMsg = null;
// we obtained some results, enter them into the list
foreach (PSPropertyExpressionResult r in expressionResults)
{
if (r.Exception == null)
{
orderValues.Add(new ObjectCommandPropertyValue(r.Result));
}
else
{
ErrorRecord errorRecord = new(
r.Exception,
"ExpressionEvaluation",
ErrorCategory.InvalidResult,
inputObject);
errors.Add(errorRecord);
orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty);
}
comparable = true;
}
}
}
/// <summary>
/// This is the row of the OrderMatrix.
/// </summary>
internal sealed class OrderByPropertyEntry
{
internal PSObject inputObject = null;
internal List<ObjectCommandPropertyValue> orderValues = new();
// The originalIndex field was added to enable stable heap-sorts (Top N/Bottom N)
internal int originalIndex = -1;
// The comparable field enables faster identification of uncomparable data
internal bool comparable = false;
}
internal sealed class OrderByPropertyComparer : IComparer<OrderByPropertyEntry>
{
internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive)
{
_propertyComparers = new ObjectCommandComparer[ascending.Length];
for (int k = 0; k < ascending.Length; k++)
{
_propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive);
}
}
public int Compare(OrderByPropertyEntry firstEntry, OrderByPropertyEntry secondEntry)
{
// we have to take into consideration that some vectors
// might be shorter than others
int order = 0;
for (int k = 0; k < _propertyComparers.Length; k++)
{
ObjectCommandPropertyValue firstValue = (k < firstEntry.orderValues.Count) ?
firstEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty;
ObjectCommandPropertyValue secondValue = (k < secondEntry.orderValues.Count) ?
secondEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty;
order = _propertyComparers[k].Compare(firstValue, secondValue);
if (order != 0)
return order;
}
return order;
}
internal static OrderByPropertyComparer CreateComparer(List<OrderByPropertyEntry> orderMatrix, bool ascendingFlag, bool?[] ascendingOverrides, CultureInfo cultureInfo, bool caseSensitive)
{
if (orderMatrix.Count == 0)
return null;
// create a comparer able to handle a vector of N entries,
// where N is the max number of entries
int maxEntries = 0;
foreach (OrderByPropertyEntry entry in orderMatrix)
{
if (entry.orderValues.Count > maxEntries)
maxEntries = entry.orderValues.Count;
}
if (maxEntries == 0)
return null;
bool[] ascending = new bool[maxEntries];
for (int k = 0; k < maxEntries; k++)
{
if (ascendingOverrides != null && ascendingOverrides[k].HasValue)
{
ascending[k] = ascendingOverrides[k].Value;
}
else
{
ascending[k] = ascendingFlag;
}
}
// NOTE: the size of the boolean array will determine the max width of the
// vectors to check
return new OrderByPropertyComparer(ascending, cultureInfo, caseSensitive);
}
private readonly ObjectCommandComparer[] _propertyComparers = null;
}
internal sealed class IndexedOrderByPropertyComparer : IComparer<OrderByPropertyEntry>
{
internal IndexedOrderByPropertyComparer(OrderByPropertyComparer orderByPropertyComparer)
{
_orderByPropertyComparer = orderByPropertyComparer;
}
public int Compare(OrderByPropertyEntry lhs, OrderByPropertyEntry rhs)
{
// Non-comparable items always fall after comparable items
if (lhs.comparable != rhs.comparable)
{
return lhs.comparable.CompareTo(rhs.comparable) * -1;
}
int result = _orderByPropertyComparer.Compare(lhs, rhs);
// When items are identical according to the internal comparison, compare by index
// to preserve the original order
if (result == 0)
{
return lhs.originalIndex.CompareTo(rhs.originalIndex);
}
// Otherwise, return the default comparison results
return result;
}
private readonly OrderByPropertyComparer _orderByPropertyComparer = null;
}
}