Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 对列表进行排序<&燃气轮机;在C中使用linq#_C#_Linq_Sorting_Datagridview - Fatal编程技术网

C# 对列表进行排序<&燃气轮机;在C中使用linq#

C# 对列表进行排序<&燃气轮机;在C中使用linq#,c#,linq,sorting,datagridview,C#,Linq,Sorting,Datagridview,我想在Datagridview ColumnHeaderMouseClick下进行“排序”。 Accending或Decenting应该是自动的,selected column value automatic 我浏览了很多网站,尝试了一些选择,但我无法实现我的目标 private void lst_Install_Item_Main_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { try

我想在Datagridview ColumnHeaderMouseClick下进行“排序”。 Accending或Decenting应该是自动的,selected column value automatic

我浏览了很多网站,尝试了一些选择,但我无法实现我的目标

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);
    }
}
private void lst\u Install\u Item\u Main\u ColumnHeaderMouseClick(对象发送器,DataGridViewCellMouseEventArgs e)
{
尝试
{
DataGridViewColumn newColumn=lst_Install_Item_Main.Columns[e.ColumnIndex];
List temp=(List)lst_Install_Item_Main.DataSource;
//var newList=temp.OrderBy(m=>m.feet.ToList();
//var newList=temp.AsQueryable().OrderBy(m=>m.feet.ToList();
温度排序((m1,m2)=>m1.英尺比(m2.英尺));
lst_Install_Item_Main.DataSource=temp;
lst_Install_Item_Main.Refresh();
}
捕获(例外情况除外)
{
MessageBox.Show(“带来排序时出错\n”+例如Message,“Testing”,MessageBoxButtons.OK,MessageBoxIcon.error);
}
}
上面的代码“排序”在“英尺”列上的列表,但

  • 我想传递用户单击的columnname,可以吗
  • 我输入了(1',21',123',5',10') 上面的代码对列表进行排序,如>>(1',10',123',21',5')

  • 但我希望输出像>>(1',5',10',21',123') 这有可能实现吗

  • 如何在这里实现上升或下降 (我的意思是,当我第一次单击时,它将执行升序操作;当第二次单击同一列时,它应该执行降序操作)


  • 非常感谢你的建议和帮助

    您必须将字符串转换为整数值,因为字符串的顺序不同(按字典顺序,
    10
    位于
    2
    之前)。此外,由于您的输入包含
    -字符,您必须首先使用删除它们

    此外,您还可以使用:


    如果按降序排列。

    则需要将
    英尺的值作为整数排序。为此,首先需要删除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,增加了排序顺序的触发器

    我建议您以这种方式使用iParer

    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;
        }
    }
    
    公共类TestComparer:IComparer
    {
    布尔伊萨丁;
    公共测试比较程序(bool isAscendingOrder)
    {
    isAscending=isAscendingOrder;
    }
    int IComparer.Compare(测试a、测试b)
    {
    int c1=IntFromStr(a.英尺);
    int c2=IntFromStr(b.英尺);
    国际关系;
    res=(c1>c2)?1:(c1
    此比较器将把无效项移到已排序列表的末尾,您也可以轻松地更改排序行为,您可以像下面这样调用它

        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));
    
    Listlst=newlist();
    //每次单击时触发值将是您的属性
    //(sortOrderTrigger=!sortOrderTrigger)
    bool sortOrderTrigger=true;
    lst.Add(新测试{feet=“1'”});
    添加(新测试{feet=“21'”});
    lst.Add(新测试{feet=“123'”});
    添加(新测试{feet=“5'”});
    添加(新测试{feet=“10'”});
    添加(新测试{feet=“15'”});
    lst.Add(新测试{feet=“jj'”});
    lst.Add(新测试{feet=“ff'”});
    lst.Sort(新的TestComparer(sortOrderTrigger));
    
    感谢您的帮助和指导。
    我已将我的要求固定如下,希望这对像我这样的人有所帮助:)

    1。创建的列表包含与columns 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;
            }
    
    private void lst\u Install\u Item\u Main\u ColumnHeaderMouseClick(对象发送器,DataGridViewCellMouseEventArgs e)
    {
    尝试
    {
    //获取单击的列
    DataGridViewColumn newColumn=lst_Install_Item_Main.Columns[e.ColumnIndex];
    //从DataGrid获取值
    List temp=(List)lst_Install_Item_Main.DataSource;
    //获取该列的排序顺序
    字符串orderby=GetOrder(newColumn.DataPropertyName);
    if(orderby==ListSortDirection.Ascending.ToString())//Ascending
    {
    if(newColumn.DataPropertyName==“feets”)//feets列使用双精度值和所需修剪进行排序
    {
    temp=temp.OrderBy(x=>Convert.ToDouble(x.feet.Trim('\'')).ToList();
    }
    else if(newColumn.DataPropertyName==“shapelen”)//shapelen列排序具有双值和所需修剪
    {
    temp=temp.OrderBy(x=>Convert.ToDouble(x.shapelen.Trim('\'')).ToList();
    }
    else///仅具有字符串值的其他列
    
    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();
                }
            }
    
    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;
            }
    
    Private List<sortList> sortOrder = new List<sortList>();
    
    sortOrder.Add(new sortList());