List<object>排序

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Configuration;

using ESRI.ArcGIS.Carto;

using ESRI.ArcGIS.Geometry;

using ESRI.ArcGIS.Geodatabase;

using ESRI.ArcGIS.DataSourcesFile;

using ESRI.ArcGIS.DataSourcesRaster;

using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.DataSourcesGDB;

using System.Reflection;

using System.Runtime.InteropServices;
using System.Collections;
namespace sandian
{
    public partial class SaDian : Form
    {

      public  XmlDocument xmldoc = new XmlDocument();

      public static XmlNodeList nodelist;

      public string[] headText = new string[10] { "路段名","起始道路","終止道路", "所處方向", "點X座標","點Y座標","序號","統計路段名","統計總計","統計重複點" };

    
        List<LuDuan> LuDuanList=new List<LuDuan>();
  

    public  System.Reflection.Missing miss;
    public static Microsoft.Office.Interop.Excel.ApplicationClass excel;
    public static Microsoft.Office.Interop.Excel.Workbooks books;
    public static Microsoft.Office.Interop.Excel.Workbook book;
    public static Microsoft.Office.Interop.Excel.Worksheet sheet;

    public static int ExcelX = 2;
    public static int ExcelY = 1;
    public static int filterDistance =30;

        public SaDian()
        {
            InitializeComponent();
             init();
        }

        public void initExcel()
        {
            miss = System.Reflection.Missing.Value;
          excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
            excel.Application.Workbooks.Add(true); ;
            //若是true,則在導出的時候會顯示EXcel界面。
            excel.Visible = true;
            if (excel == null)
            {
                MessageBox.Show("EXCEL無法啓動!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
            book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
             sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
            sheet.Name = "test";
            //生成字段名稱,逐條寫,無效率
            for (int i = 0; i < headText.Length; i++)
            {
                excel.Cells[1, i + 1] = headText[i];
            }
        
        }



        public void init()
        {
            xmldoc.Load("setup.xml");
            nodelist = xmldoc.SelectSingleNode("setup").ChildNodes;//第一個節點
           // initExcel();
        }


        private void button1_Click(object sender, EventArgs e)
        {
           // string MxdPath = OpenMxd();
           // axMapControl1.LoadMxFile(MxdPath);
           // axMapControl1.AddShapeFile();
            string[] ShpFile=OpenShapeFile();

            string FilePath = ShpFile[0];
            string ShpName = ShpFile[1];
            axMapControl1.AddShapeFile(FilePath, ShpName);
            
        }

        public string OpenMxd()
        {

            string MxdPath = "";
            OpenFileDialog OpenMXD = new OpenFileDialog();
            OpenMXD.Title = "打開地圖";
            OpenMXD.InitialDirectory = "E:";
            OpenMXD.Filter = "Map Documents (*.mxd)|*.mxd";
            if (OpenMXD.ShowDialog() == DialogResult.OK)
            {
                MxdPath = OpenMXD.FileName;
            }
            return MxdPath;
        }

        //選擇shape文件
        public string[] OpenShapeFile()
        {
            string[] ShpFile = new string[2];
            OpenFileDialog OpenShpFile = new OpenFileDialog();
            OpenShpFile.Title = "打開Shape文件";
            OpenShpFile.InitialDirectory = "E:";
            OpenShpFile.Filter = "Shape文件(*.shp)|*.shp";
            if (OpenShpFile.ShowDialog() == DialogResult.OK)
            {
                string ShapPath = OpenShpFile.FileName;
                //利用"\\"將文件路徑分成兩部分
                int Position = ShapPath.LastIndexOf("\\");
                string FilePath = ShapPath.Substring(0, Position);
                string ShpName = ShapPath.Substring(Position + 1);
                ShpFile[0] = FilePath;
                ShpFile[1] = ShpName;
            }
            return ShpFile;
        }

        //讀取shape文件,新建圖層,並顯示在地圖
        private void button2_Click(object sender, EventArgs e)
        {
           // IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); // 1
           // IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile();


            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); // 1

            string[] ShpFile = OpenShapeFile();

            string FilePath = ShpFile[0];
            string ShpName = ShpFile[1];

            MessageBox.Show(FilePath);
            MessageBox.Show(ShpName);

            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0); // 2

            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

            IFeatureClass pFC = pFeatureWorkspace.OpenFeatureClass(ShpName); //3


            IFeatureLayer pFLayer = new FeatureLayerClass(); // 4

            pFLayer.FeatureClass = pFC;

            pFLayer.Name = pFC.AliasName; // 5

            ILayer pLayer = pFLayer as ILayer;


            IMap pMap = axMapControl1.Map;

            pMap.AddLayer(pLayer); // 6

            axMapControl1.ActiveView.Refresh();

        }
        // 計算兩點之間的距離    
            private static double lineSpace(double x1, double y1,double x2, double y2) {    
                double lineLength = 0;
                lineLength = Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2)*(y1 - y2));       
                    
                return lineLength;    
                  
            }


            public static string FangXiang(double x1, double y1, double x2, double y2, double x0, double y0)
            {
                double s = 0;
                s = (x1 - x0) * (y2 - y0) - (y1 - y0) * (x2 - x0);
                if (s > 0)
                {
                    return "逆時針";
                }
                if (s == 0)
                {
                    return "在一條線上";
                
                }
                if (s < 0)
                {
                    return "順時針";
                
                }
                return "未處理結果";
            
            
            }
               //點到線段距離  
            private static double pointToLine(double x1, double y1,  double x2, double y2,  double x0, double y0)    
                 {    
                    double space = 0;    
                    double a, b, c;    
                    a = lineSpace(x1, y1, x2, y2);// 線段的長度    
                    b = lineSpace(x1, y1, x0, y0);// (x1,y1)到點的距離    
                    c = lineSpace(x2, y2, x0, y0);// (x2,y2)到點的距離    
                    if (c <= 0.000001 || b <= 0.000001) {
                        space = 1000000;    
                        return 1000000;    
                    }    
                    if (a <= 0.000001) {
                        space = 1000000;
                        return 1000000;    
                    }    
                    if (c * c >= a * a + b * b) {
                        space = 1000000;
                        return 1000000;    
                    }    
                    if (b * b >= a * a + c * c) {
                        space = 1000000;
                        return 1000000;    
                    }    
                     double p = (a + b + c) / 2;// 半周長    
                     double s = Math.Sqrt(p * (p - a) * (p - b) * (p - c));// 海倫公式求面積    
                    space = 2 * s / a;// 返回點到線的距離(利用三角形面積公式求高)    
                    return space;    
                }    

        public static int doQueryShape(string startName,string endName,string lutemp,IPolyline pLine,IGeometry bufferGeometry)
        {
            string luduanName = lutemp;
               double d = pLine.Length;
             IPoint spPoint = new PointClass();
             pLine.QueryPoint(esriSegmentExtension.esriNoExtension, 0, false, spPoint);

             IPoint mpPoint = new PointClass();
             pLine.QueryPoint(esriSegmentExtension.esriNoExtension,d,false,mpPoint);




           //pLine.QueryPoint(esriSegmentExtension.esriNoExtension,0,false,
            string FilePath = @"D:\撒點";
            string ShpName="全市站牌.shp";
            IWorkspaceFactory pWorkspaceFactory = new ShapefileWorkspaceFactory(); // 1

            IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0); // 2

            IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

            IFeatureClass pFC = pFeatureWorkspace.OpenFeatureClass(ShpName); //3

            IFeatureLayer pFLayer = new FeatureLayerClass(); // 4

            pFLayer.FeatureClass = pFC;

            //IQueryFilter qf = new QueryFilterClass();
            //qf.WhereClause = "";

            pFLayer.SpatialReference = bufferGeometry.SpatialReference;

           // IGeometry geo = bufferGeometry.Envelope;
          //  (geo as IEnvelope).Expand(1000, 1000, false);

            ISpatialFilter pSpatialFilter = new SpatialFilterClass();
            pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
            pSpatialFilter.Geometry = bufferGeometry;

           // IFeatureSelection pFeatureSelection = pFLayer as IFeatureSelection;
           // pFeatureSelection.SelectFeatures(pSpatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false);

            //QI到ISelectionSet
           // ISelectionSet pSelectionSet = pFeatureSelection.SelectionSet;
           // int i = 0;
           // i = pSelectionSet.Count;
           // return i;
            IFeatureCursor featureCursor = pFLayer.Search(pSpatialFilter, false);

            //IFeatureCursor featureCursor = pFLayer.Search(qf, false);

            ESRI.ArcGIS.Geodatabase.IFeature pFeature = featureCursor.NextFeature();
            int i = 0;

            int p = 0;
            while (pFeature != null)
            {
              
            
                Multipoint mp = pFeature.Shape as Multipoint;
                for (int g = 0; g < mp.PointCount; g++)
                {

                    IPoint point1 = mp.get_Point(g);
                 
                    double distance=pointToLine(spPoint.X, spPoint.Y, mpPoint.X,mpPoint.Y,point1.X,point1.Y);
                    string direct = FangXiang(spPoint.X, spPoint.Y, mpPoint.X, mpPoint.Y, point1.X, point1.Y);
                    if (distance < 30)
                    {
                        Boolean MrRight = true;
                        
                        for (int k = g + 1; k < mp.PointCount; k++)
                        { 
                          if(lineSpace(point1.X,point1.Y,mp.get_Point(k).X,mp.get_Point(k).Y)<filterDistance)
                          {
                              MrRight = false;
                              p++;

                          }
                         
                        
                        }

                        if (MrRight == true)
                        {
                            i++;
                            //  Console.WriteLine(luduanName + ":  符合的" + direct + "點座標:" + "X=" + point1.X + "  Y=" + point1.Y + "  所處位置" + i.ToString());

                            excel.Cells[ExcelX, 1] = luduanName;
                            excel.Cells[ExcelX, 2] = startName;
                            excel.Cells[ExcelX, 3] = endName;
                            excel.Cells[ExcelX, 4] = direct;
                            excel.Cells[ExcelX, 5] = point1.X.ToString();

                            excel.Cells[ExcelX, 6] = point1.Y.ToString();

                            excel.Cells[ExcelX, 7] = i.ToString();

                            ExcelX += 1;
                        }


                    
                    }
                   

                }
                pFeature = featureCursor.NextFeature();
            }

            if (i > 0)
            {

               // excel.get_Range(excel.Cells[ExcelX, 8], excel.Cells[ExcelX, 10]).Font.Color = ColorTranslator.ToOle(Color.);
                excel.Cells[ExcelX, 8] = luduanName;

                excel.Cells[ExcelX, 9] ="總計:"+ i.ToString();

                excel.Cells[ExcelX, 10] ="重複點:"+ p.ToString();
                excel.get_Range(excel.Cells[ExcelX, 8], excel.Cells[ExcelX, 10]).Interior.ColorIndex = 6;

                ExcelX += 1;
            }

           

            return i;
        }
  

      
        public static string Get_Xml(string xml_name)
        {

           
            
            string rusult = nodelist.Item(0).SelectSingleNode(xml_name).InnerText;
            return rusult;
        }

      
        private void button3_Click(object sender, EventArgs e)
        {

             /*
                     * 獲取保存EXCEL的路徑
                     */
                    saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                    saveFileDialog.FilterIndex = 0;
                    saveFileDialog.RestoreDirectory = true;
                    saveFileDialog.CreatePrompt = true;
                    saveFileDialog.Title = "導出文件保存路徑";
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        //strName儲存保存EXCEL路徑
                        string strName = saveFileDialog.FileName;
                        if (strName.Length != 0)
                        {
                            initExcel();



                            string sdeServer = Get_Xml("SDEServer");
                            string sdeInstance = Get_Xml("SDEInstance");
                            string sdeDatabase = Get_Xml("SDEDatabase");
                            string sdeUser = Get_Xml("SDEUser");
                            string sdePassword = Get_Xml("SDEPwd");
                            string sdeVersion = Get_Xml("SDEVersion");
                            double bufferDis = Convert.ToDouble(Get_Xml("bufferDistance"));
                            double filterDis = Convert.ToDouble(Get_Xml("filterDistance"));
                            IWorkspaceFactory sdeWorkspaceFactory;
                            IFeatureWorkspace workSpace;

                            try
                            {
                                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop);

                                //授權信息加載

                                ESRI.ArcGIS.esriSystem.IAoInitialize m_AoInitialize = new ESRI.ArcGIS.esriSystem.AoInitialize();
                                m_AoInitialize.Initialize(ESRI.ArcGIS.esriSystem.esriLicenseProductCode.esriLicenseProductCodeArcInfo);


                                //進行license控件的初始化
                                IAoInitialize m_pAoInit = new AoInitializeClass();
                                m_pAoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

                                IPropertySet propSet = new PropertySetClass();
                                propSet.SetProperty("SERVER", sdeServer);
                                propSet.SetProperty("INSTANCE", sdeInstance);
                                propSet.SetProperty("USER", sdeUser);
                                propSet.SetProperty("PASSWORD", sdePassword);
                                propSet.SetProperty("DATABASE", sdeDatabase);
                                propSet.SetProperty("VERSION", sdeVersion);

                                sdeWorkspaceFactory = new SdeWorkspaceFactoryClass();
                                workSpace = (IFeatureWorkspace)sdeWorkspaceFactory.Open(propSet, 0);

                                //   MessageBox.Show("數據庫練級成功!");
                                //得到路段圖層
                                IFeatureClass pFCLuDuan = (workSpace as IFeatureWorkspace).OpenFeatureClass("路段");

                                IFeatureLayer pFLLuDuan = new FeatureLayer();
                                pFLLuDuan.FeatureClass = pFCLuDuan;
                                pFLLuDuan.Name = "路段";



                                //創建路段圖層過濾器
                                IQueryFilter pQueryFilter = new QueryFilterClass();
                                pQueryFilter.WhereClause = "所屬區縣=" + "'浦東新區'";

                                //獲得路段圖層遊標
                                IFeatureCursor pFeatureCursor = pFLLuDuan.FeatureClass.Search(pQueryFilter, false);

                                IFeature pFeature = pFeatureCursor.NextFeature();
                             

                                while (pFeature != null)
                                {

                                    IPolyline pLine = pFeature.Shape as IPolyline;

                                    IGeometry bufferGeometry = bufferPolyLine(pLine, bufferDis);


                                    object luduanName = pFeature.get_Value(pFeature.Fields.FindField("路段名稱"));
                                    string luTemp = luduanName.ToString();
                                    //  MessageBox.Show("緩衝了!");

                                    string startName = pFeature.get_Value(pFeature.Fields.FindField("起始道路")).ToString();
                                    string endName = pFeature.get_Value(pFeature.Fields.FindField("終止道路")).ToString();

                                    //targetArr[ax, 0] = startName;
                                    //targetArr[ax, 1] = endName;
                                    //targetArr[ax, 2] = luTemp;
                                    //targetArr[ax, 3] = pLine;
                                    //targetArr[ax, 4] = bufferGeometry;
                                    //ax += 1;
                                  
                                    LuDuanList.Add(new LuDuan(){ _startName = startName, _endName = endName, _luTemp = luTemp, _pLine = pLine, _bufferGeometry = bufferGeometry });
                              
                                  //  int temp = doQueryShape(startName,endName,luTemp, pLine, bufferGeometry);
                                    //  MessageBox.Show(temp.ToString());
                                    // Console.WriteLine(luduanName.ToString()+"  "+temp.ToString());
                                    pFeature = pFeatureCursor.NextFeature();

                                }
                                //  string strName = @"D:\撒點\撒點統計.xls";
                                //Console.WriteLine(targetArr[0,0].ToString());
                                //for (int kk = 0; kk < targetArr.Length; kk++)
                                //{
                                //    string p1 = targetArr[kk, 0].ToString();
                                //    string p2 = targetArr[kk,1].ToString();
                                //    string p3 = targetArr[kk, 2].ToString();
                                //    IPolyline p4 = targetArr[kk, 3] as IPolyline;
                                //    IGeometry p5 = targetArr[kk, 4] as IGeometry;
                                //    doQueryShape(p1,p2,p3,p4,p5);
                                
                                //}
                                LuDuanList.Sort(new SortName());

                                foreach (LuDuan item in LuDuanList)
                                {

                               
                                   // Console.WriteLine(item._luTemp);
                                    doQueryShape(item._startName, item._endName, item._luTemp,item._pLine,item._bufferGeometry);
                                }
                              

                                sheet.SaveAs(strName, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                                book.Close(false, miss, miss);
                                excel.Quit();
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                                System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
                                GC.Collect();

                               

                                ILayer pLayer = pFLLuDuan as ILayer;


                                IMap pMap = axMapControl1.Map;

                                pMap.AddLayer(pLayer);

                                axMapControl1.ActiveView.Refresh();

                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }

                        }
                    }



        }


        public IGeometry bufferPolyLine(IPolyline pPolyline, double dis)
        {
            ITopologicalOperator topolOperator = pPolyline as ITopologicalOperator;
            IGeometry bufferGeometry = topolOperator.Buffer(dis);
            return bufferGeometry;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            //進行license控件的初始化
           // IAoInitialize m_pAoInit = new AoInitializeClass();
          //  m_pAoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcServer);

                string FilePath = @"D:\sd";
                string ShpName = "全市站牌.shp";
                IWorkspaceFactory pWorkspaceFactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory(); // 1
                IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(FilePath, 0); // 2

                IFeatureWorkspace pFeatureWorkspace = pWorkspace as IFeatureWorkspace;

                IFeatureClass pFC = pFeatureWorkspace.OpenFeatureClass(ShpName); //3


                IFeatureLayer pFLayer = new FeatureLayerClass(); // 4

                pFLayer.FeatureClass = pFC;

                pFLayer.Name = pFC.AliasName; // 5

                ILayer pLayer = pFLayer as ILayer;


                IMap pMap = axMapControl1.Map;

                pMap.AddLayer(pLayer); // 6

                axMapControl1.ActiveView.Refresh();
          
           
        }
    }
}

class LuDuan : IComparable<LuDuan>
{
    public string _startName { get; set; }
     public string _endName { get; set; }
     public string _luTemp { get; set; }
    public IPolyline _pLine {get;set;}
    public IGeometry _bufferGeometry {get;set;}
   

    #region IComparable<Student> Members

    public int CompareTo(LuDuan other)
    {
        return _luTemp.CompareTo(other._luTemp);
    }

    #endregion
}
class SortName : IComparer<LuDuan>
{
    #region IComparer<LuDuan> Members

    public int Compare(LuDuan x, LuDuan y)
    {
        return x._luTemp.CompareTo(y._luTemp);
    }

    #endregion
}
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章