日期:2014-05-20  浏览次数:21020 次

linq给二维数组排序


  int[,] numArr = new int[,] { { 4, 4 }, { 3, 3 }, { 5, 5 }, { 2, 2 }, { 1, 1 } }
根据第一个维度从大到小排序

如果是引用类型如何排序

//(DrawMapping) LatPos.X,LatPos.X
//(DrawMapping) service.GetMappingPosition(LatPos[] latArr);        //方法重载
//(DrawMapping) service.GetMappingPosition(List<LatPos> latList);   //方法重载
//(DrawMapping) service.GetMappingPosition(string[,] latStrArr);    //方法重载

LatPos[] latArr=new LatPos[myPos.length];
latArr[0]=new LatPos(4,4);
latArr[1]=new LatPos(3,3);
latArr[2]=new LatPos(1,1);
latArr[3]=new LatPos(6,6);
latArr[4]=new LatPos(7,7);
通过Linq给以上数组排序根据位置的第一个参数从大到小

service.GetMappingPosition(LatPos[] latArr); 
service.GetMappingPosition(List<LatPos> latList);
service.GetMappingPosition(string[,] latStrArr);

------解决方案--------------------
操作多维数组, 这不是LINQ干的活,你最好重新定义你的数据结构

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] numArr = new int[,] { { 4, 11 }, { 3, 13 }, { 5, 15 }, { 2, 12 }, { 1, 10 } };
            var query = numArr.AsEnumerable().OrderByDescending(n => n);
            query.ToList().ForEach(q => Console.WriteLine(q));
            Console.ReadKey();
        }
    }

    public static class HelperClass
    {
        public static IEnumerable<T> AsEnumerable<T>(this T[,] myArr)
        {
            for (int i = 0; i < myArr.GetLength(0); i++)
                yield return myArr[i, 0];
        }
    }
}

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {        
        static void Main(string[] args)
        {
            int[,] numArr = new int[,] { { 4, 4 }, { 3, 3 }, { 5, 5 }, { 2, 2 }, { 1, 1 }, { 3, 1 } };
            int[,] result = new int[numArr.GetLength(0), numArr.GetLength(1)];
            var query = Enumerable.Range(0, numArr.GetLength(0)).Select(x => new { v = numArr[x, 0], x })
                .OrderBy(x => x.v).Select((x, i) => new { x.x, i }).ToDictionary(x => x.i, x => x.x);
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)
                {
                    result[i, j] = numArr[query[i], j];
                }
            }
            for (int i = 0; i < result.GetLength(0); i++)
            {
                for (int j = 0; j < result.GetLength(1); j++)