将datagridview中的行排列为行值之和 [英] Sort rows in datagridview by the sum of rows values

查看:181
本文介绍了将datagridview中的行排列为行值之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 DataGridView ,单元格的值为 bool true false 。我需要根据真值计算排序行。具有最真实单元格的行应该在顶部,而在底部最不重要的行。

I have DataGridView and cells have value bool values true or false. I Need to sort rows based on having count of true values. The row which has most true cells should be at top and the row with least true values at bottom.

数据在Access数据库中,我使用 TableAdapter

Data is in an Access database and I load data using TableAdapter.

推荐答案

您可以使用以下选项之一:

You can use either of these options:


  • 您可以加载从数据库。

  • 您可以通过将计算列添加到 DataTable 来排序数据。

  • 您可以排序使用linq的数据

  • You can load data sorted from database.
  • You can sort data by adding a computed column to DataTable.
  • You can sort data using linq.

使用DataTable的计算列

向表中添加一个新列,并设置 表达式 。然后使用 DefaultView.Sort 属性的数据表:

Add a new column to the table, and set Expression of the column. Then sort table using DefaultView.Sort property of data table:

table.Columns.Add("Value4", typeof(int), 
          "Convert(ISNULL(Value1,false), 'System.Int32') + " +
          "Convert(ISNULL(Value2,false), 'System.Int32') + " +
          "Convert(ISNULL(Value3,false), 'System.Int32')" );

table.DefaultView.Sort = "Value4 DESC";
this.dataGridView1.DataSource = table;

使用Linq

您可以使用 OrderByDescending 根据行中真实值的计数排序行:

You can use OrderByDescending to sort rows based on count of true values in a row this way:

var temp = table.Clone();
table.Rows.Cast<DataRow>()
     .OrderByDescending(x => x.ItemArray.OfType<bool>().Count(b=>b==true))
     .ToList().ForEach(x =>
     {
         temp.Rows.Add(x.ItemArray);
     });
this.dataGridView1.DataSource = temp;

这篇关于将datagridview中的行排列为行值之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆