Convert LINQ orderby to sort list of places

I am currently sorting a list using LINQ for objects, and then ToList()based on the results:

var SortedPossibleMoveLocations = (from PML in PossibleMoveLocations
                                   orderby Randomiser.Next()
                                   orderby IsSameType(PML) ? (_Owner[PML] as TileFlowing).UnitsWithin : 0
                                   orderby PossibleMoveLocationOrdering(PML)
                                   select PML).ToList();

I want to convert this to do inplace sorting, I think using a method List<T>.Sort(). If I only ordered one thing, I would know how to do it, however, when I order PossibleMoveLocationOrdering(which returns int) and then IsSameType(PML) ? (_Owner[PML] as TileFlowing).UnitsWithin : 0that calculates int, then on Randomiser.Next()(which returns a random int), I don’t know how to do it.

Question: How to write a comparison function (or is there a better method) to execute a LINQ type query above.

+5
source share
2

orderby - - , .

Randomiser.Next() , .

LINQ ( Randomiser ):

var query = (from PML in PossibleMoveLocations
             orderby PossibleMoveLocationOrdering(PML),
                     IsSameType(PML) ? (_Owner[PML] as TileFlowing).UnitsWithin : 0,
                     Randomiser.Next()
             select PML).ToList();

:

var query = PossibleMoveLocations
                .OrderBy(pml => PossibleMoveLocationOrdering(PML))
                .ThenBy(pml => IsSameType(pml) ? 
                                    (_Owner[pml] as TileFlowing).UnitsWithin : 0)
                .ThenBy(pml => Randomiser.Next())
                .ToList();

Comparison<T> IComparer<T>, , , . ( Marc), , , MiscUtil:

var comparer = ProjectionComparer<PossibleMove>
                   .Create(pml => PossibleMoveLocationOrdering(PML));
                   .ThenBy(pml => IsSameType(pml) ? ...)
                   .ThenBy(...);

list.Sort(comparer);

, Randomizer , , , ( )... , x < y < z < x.

+10

:

list.Sort((x,y) => {
    int result = /* first comparison, for example
                    string.Compare(x.Name, y.Name) */
    if (result == 0) result = /* second comparison,
                                 for example x.Id.CompareTo(y.Id) */
    ...
    if (result == 0) result = /* final comparison */
    return result;
});

(, , ).

+6

All Articles