簡體   English   中英

在C#中使用linq對List <>進行排序

[英]Sorting a List<> using linq in C#

我想在Datagridview ColumnHeaderMouseClick下進行“排序”。 遞增或遞減應該是自動的,選擇的列值是自動的。

我瀏覽了許多網站並嘗試了一些選項,但我無法實現自己的目標。

private void lst_Install_Item_Main_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    try
    {
        DataGridViewColumn newColumn = lst_Install_Item_Main.Columns[e.ColumnIndex];
        List<test> temp = (List<test>)lst_Install_Item_Main.DataSource;

        //var newList = temp.OrderBy(m => m.feet).ToList();
        //var newList = temp.AsQueryable().OrderBy(m => m.feet).ToList();
        temp.Sort((m1, m2) => m1.feet.CompareTo(m2.feet));

        lst_Install_Item_Main.DataSource = temp;
        lst_Install_Item_Main.Refresh();
    }
    catch (Exception ex)
    {
        MessageBox.Show("There was an error bringing sorting \n" + ex.Message, "Testing", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

上面的代碼“排序”“腳”列上的列表,但是

  1. 我想傳遞用戶單擊的列名,這可能嗎?

我已經輸入了(1',21',123',5',10')之類的代碼以上代碼對列表進行了排序,例如>>(1',10',123',21',5')

  1. 但是我想要輸出>>(1',5',10',21',123')這樣的輸出嗎?

  2. 如何在此處實現升序或降序(我的意思是,當我第一次單擊時,它將進行升序;第二次單擊同一列時,則需要進行降序)

非常感謝您的建議幫助。

您必須將字符串轉換為整數值,因為字符串的順序不同(按字典順序, 102之前)。 此外,由於您的輸入包含'字符,您必須首先使用String.Trim('\\'')刪除它們。

temp.Sort((m1, m2) => Convert.ToInt32(m1.feet.Trim('\'')).CompareTo(Convert.ToInt(m2.feet.Trim('\''))));

另外,您也可以使用Linq-OrderBy

temp = temp.OrderBy(x => Convert.ToInt32(x.feet.Trim('\''))).ToList();

以及OrderByDescending如果降序排列)。

您需要將feet的值排序為整數。 為此,您首先需要刪除英尺符號( ' ),然后將值解析為一個int (臨時,該值仍存儲為字符串)。

這應該可以解決問題:

temp.Sort((m1, m2) => int.Parse(m1.feet.Replace("'", "")).CompareTo(int.Parse(m2.feet.Replace("'", ""))));

另外,我建議您不要在值中存儲英尺符號,而是在網格中顯示值時使用某種格式將其包括在內。 這樣,您每次需要使用值時就可以避免進行此類轉換和比較。

如果沒有負值,則要根據需要進行排序,您需要將值解析為數字或簡單地填充它們:

temp.Sort((m1, m2) => m1.feet.PadLeft(2).CompareTo(m2.feet.PadLeft(2)));

比較字符串"1""5""10"將改為比較" 1"" 5""10" (注意,空格少於0字符),使它們以正確的順序排序。

確保選擇足夠大的數字以覆蓋填充到最長的數字。

問題3已更新,為排序順序添加了觸發器

我建議您以這種方式使用ICoparer

public class TestComparer : IComparer<test>
{
    bool isAscending;

    public TestComparer(bool isAscendingOrder)
    {
        isAscending = isAscendingOrder;
    }

    int IComparer<test>.Compare(test a, test b)
    {
        int c1 = IntFromStr(a.feet);
        int c2 = IntFromStr(b.feet);
        int res;
        res = (c1 > c2) ? 1 : (c1 < c2) ? -1 : 0;
        return isAscending ? res : -res;
    }

    int IntFromStr(string s)
    {
        int result;
        return (int.TryParse(s.Replace("'", ""), out result)) ? result : int.MaxValue;
    }
}

此比較器會將無效的項目移到已排序列表的末尾,您也可以輕松更改自己的排序行為,如下所示

    List < test > lst = new List<test>();
    // It will be your property to Trigger value each time you click
    // (sortOrderTrigger = !sortOrderTrigger)
    bool sortOrderTrigger = true;

    lst.Add(new test { feet = "1'" });
    lst.Add(new test { feet = "21'" });
    lst.Add(new test { feet = "123'" });
    lst.Add(new test { feet = "5'" });
    lst.Add(new test { feet = "10'" });
    lst.Add(new test { feet = "15'" });
    lst.Add(new test { feet = "jj'" });
    lst.Add(new test { feet = "ff'" });

    lst.Sort(new TestComparer(sortOrderTrigger));

感謝您的所有幫助和指導。 我已將要求固定如下,希望對我這樣的人有所幫助:)

1.創建的列表包含與列dataproperty相同的列。

public class sortList
        {
            public string Layer { get; set; }
            public string mlenth { get; set; }
            public string diameter { get; set; }
            public string subtypecd { get; set; }
            public string coatingtype { get; set; }
            public string year { get; set; }
            public string gisid { get; set; }
            public string taxdistrict { get; set; }
            public string lengthsource { get; set; }
            public string shapelen { get; set; }
            public string feet { get; set; }    

            public sortList()
            {
                this.Layer = ListSortDirection.Ascending.ToString();
                this.mlenth = ListSortDirection.Ascending.ToString();
                this.feet = ListSortDirection.Ascending.ToString();
                this.diameter = ListSortDirection.Ascending.ToString();
                this.subtypecd = ListSortDirection.Ascending.ToString();
                this.coatingtype = ListSortDirection.Ascending.ToString();
                this.year = ListSortDirection.Ascending.ToString();
                this.gisid = ListSortDirection.Ascending.ToString();
                this.taxdistrict = ListSortDirection.Ascending.ToString();
                this.lengthsource = ListSortDirection.Ascending.ToString();
                this.shapelen = ListSortDirection.Ascending.ToString();
            }
        }

2. ColumnHeaderMouseClick事件和順序函數上的書面代碼

private void lst_Install_Item_Main_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                //Get Column which clicked
                DataGridViewColumn newColumn = lst_Install_Item_Main.Columns[e.ColumnIndex];
                //Get Values from DataGrid
                List<test> temp = (List<test>)lst_Install_Item_Main.DataSource;

                //Get the sorting order for that column
                string orderby = GetOrder(newColumn.DataPropertyName);

                if (orderby == ListSortDirection.Ascending.ToString()) //Ascending
                {
                    if (newColumn.DataPropertyName == "feet") //Feet column sort with double value and required trim
                    {
                        temp = temp.OrderBy(x => Convert.ToDouble(x.feet.Trim('\''))).ToList();
                    }
                    else if (newColumn.DataPropertyName == "shapelen") //Shapelen column sort with double value and required trim
                    {
                        temp = temp.OrderBy(x => Convert.ToDouble(x.shapelen.Trim('\''))).ToList();
                    }
                    else ///other columns having string value only.
                    {
                        temp = temp.OrderBy(x => x.GetType().GetProperty(newColumn.DataPropertyName).GetValue(x, null)).ToList();
                    }
                }
                else // Descending 
                {
                    if (newColumn.DataPropertyName == "feet") //Feet column sort with double value and required trim
                    {
                        temp = temp.OrderByDescending(x => Convert.ToDouble(x.feet.Trim('\''))).ToList();
                    }
                    else if (newColumn.DataPropertyName == "shapelen")  //Shapelen column sort with double value and required trim
                    {
                        temp = temp.OrderByDescending(x => Convert.ToDouble(x.shapelen.Trim('\''))).ToList();
                    }
                    else //other columns having string value only.
                    {
                        temp = temp.OrderByDescending(y => y.GetType().GetProperty(newColumn.DataPropertyName).GetValue(y, null)).ToList();
                    }
                }
                lst_Install_Item_Main.DataSource = temp;
                lst_Install_Item_Main.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("There was an error while sorting \n" + ex.Message, "Closeout Calculator", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetOrder(string columnName)
        {
            //Store the each coulmn(Ascending/Descending) values to make it dynamic 
            string ord = sortOrder[0].GetType().GetProperty(columnName).GetValue(sortOrder[0], null).ToString();
            if (ord == ListSortDirection.Ascending.ToString())
            {
                sortOrder[0].GetType().GetProperty(columnName).SetValue(sortOrder[0], ListSortDirection.Descending.ToString(), null);
            }
            else
            { sortOrder[0].GetType().GetProperty(columnName).SetValue(sortOrder[0], ListSortDirection.Ascending.ToString(), null); }
            return ord;
        }

3.排序列表初始化,並在構造方法中聲明obj。

Private List<sortList> sortOrder = new List<sortList>();

sortOrder.Add(new sortList());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM