使用list <string>和方法按字母顺序从MySQL排序数据,以在C#中返回排序后的列表

时间:2019-04-21 17:46:26

标签: c# mysql sorting alphabetical-sort

我正在从MySQL数据库文件中提取数据,并将其中的三个数据项加载到称为索引的方法中,该方法提取“名称”,“姓氏”和“电话号码”字段.....主要目标是按字母顺序加载所有数据按姓氏字母排列,如果两个姓氏匹配,则应按字母顺序对它们进行排序。

using Data_Layer;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Business_Logic_Layer
{
    public class BusinessLogic
    {
        public List<PhoneIndex> phoneIndex = new List<PhoneIndex>();

        public void createPhoneIndex()
        {
            string tableName = "customers";

            DataConnection dc = new DataConnection();
            DataSet customers = dc.selectData(tableName);

            foreach (DataRow customer_row in customers.Tables[0].Rows)
            {
                string surname, name, telephone;
                surname = name = telephone = "";

                for (int i = 0; i < customers.Tables[0].Columns.Count; i++)
                {
                    if (customers.Tables[0].Columns[i].ColumnName.StartsWith("contactFirstName"))
                    {
                        name = customer_row.ItemArray[i].ToString();
                    }
                    else if (customers.Tables[0].Columns[i].ColumnName.StartsWith("contactLastName"))
                    {
                        surname = customer_row.ItemArray[i].ToString();
                    }
                    else if (customers.Tables[0].Columns[i].ColumnName.StartsWith("phone"))
                    {
                        telephone = customer_row.ItemArray[i].ToString();
                    }
                }

                // Add the information to the main phoneIndex

                bool added = false;

                PhoneIndexEntry temp_index_entry = new PhoneIndexEntry() { name = name, surname = surname, telephone = telephone };

                for (int i = 0; i < phoneIndex.Count; i++)
                {
                    if (surname.StartsWith(phoneIndex[i].letter))
                    {
                        phoneIndex[i].entries.Add(temp_index_entry);
                        added = true;
                    }
                }

                if (!added)
                {
                    PhoneIndex temp_index = new PhoneIndex() { letter = surname.Substring(0, 1), entries = new List<PhoneIndexEntry>() { temp_index_entry } };
                    phoneIndex.Add(temp_index);
                    added = true;
                }

            }
        } // End of method createPhoneIndex()




        public void sortPhoneIndex()
        {


            // Your code goes here...
            string surname, name;
            surname = name = "";
            List<PhoneIndex> phoneIndex = new List<PhoneIndex>() { };

            PhoneIndexEntry temp_index_entry = new PhoneIndexEntry() { name = name, surname = surname };

            foreach (PhoneIndex index in phoneIndex)//letter, entries sort through letters
            { 

                            string[] sortedLetter = new string[1];

                            for (int i = 0; i < phoneIndex.Count - 1; i++)
                            {
                                for (int j = i + 1; j < phoneIndex.Count; j++)
                                {
                                    if (phoneIndex[i].letter.CompareTo(phoneIndex[j].letter) > 0)
                                    {
                                        sortedLetter[0] = phoneIndex[i].letter;
                                        phoneIndex[i].letter = phoneIndex[j].letter;
                                        phoneIndex[j].letter = sortedLetter[0];
                                    }
                                }
                            }
                //if name==name compare surname for sorting
                return;
                        }

                    }//end of foreach

                } // End of method sortPhoneIndex()

        } // End of Class BusinessLogic



        public class PhoneIndex
        {
            public string letter { get; set; }
            public List<PhoneIndexEntry> entries { get; set; }


        } // End of Class PhoneIndex

        public class PhoneIndexEntry
        {
            public string name { get; set; }
            public string surname { get; set; }
            public string telephone { get; set; }

        } // End of Class PhoneIndexEntry


// End of Namespace Business_Logic_Layer

A =

安东尼,亚当斯,0670510248

B = 比尔亚当斯0724677987 比尔,坩埚,0687944987

1 个答案:

答案 0 :(得分:0)

假设您无法更改从数据库中检索数据的方式,那么Linq可以轻松完成此工作。

// Example data .....
DataTable dt = new DataTable();
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("surname", typeof(string));
dt.Columns.Add("phone", typeof(string));
dt.Rows.Add("charles", "dickens", "11232");
dt.Rows.Add("mark", "twain", "453446");
dt.Rows.Add("howard", "lovecraft", "875564");
dt.Rows.Add("ernst", "hemingway", "1647567");
dt.Rows.Add("thomas", "mann", "56434");
dt.Rows.Add("isaac", "asimov", "9700");
dt.Rows.Add("aldous", "huxley", "2654");


List<PhoneIndex> phoneIndex = new List<PhoneIndex>();

// Let's enumerate the datatable grouping by first letter in the surname column
var names = dt.AsEnumerable().GroupBy(d => d.Field<string>("surname").Substring(0, 1))
         // foreach group build a sublist with the info from the datarow 
         // transformed in a PhoneIndexEntry.
         .Select(g => g.Select(p => new PhoneIndexEntry 
         {
             name = p.Field<string>("name"),
             surname = p.Field<string>("surname"),
             telephone = p.Field<string>("phone")

         }));

// Now we have an IEnumerable<IEnumerable> where the first enumerable is a list 
// of all distinct first letter from the surname column, while the second
// is an enumerable of PhoneIndexEntry. 
// We can loop over the first Enumerable ordering it
// by the first surname's letter and creating a PhoneIndex with all the PhoneIndexEntry for that specific letter
foreach (var entry in names.OrderBy(n => n.First().surname[0].ToString()))
    phoneIndex.Add(new PhoneIndex { letter = entry.First().surname[0].ToString(), entries = entry.OrderBy(s => s.surname).ToList()});

旁注:看来您有一个非常糟糕的 do_it_all 方法(SelectData),该方法在其中传递表名并从该表中取回所有数据。
当然,这不是查询数据库的好方法,除非您检索的记录很少,否则建议您为每次数据提取编写特定的方法,或者花一些时间来学习如何使用ORM库。