How to filter certain DataRows in a Data Table
I have a DataTable like the one above, what is the efficient way to filter the rows
something like below,
How to extract the rows which differs by the Col5
Thanks
I think that you may use ToTable(distinct, columns) method of System.Data.DataView. Below is the code sample:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Col1", "Col2" ,"Col3","Col4","Col5");
// DataTable dt = new DataTable(); for (int i = 1; i < 6; i++) dt.Columns.Add("Col" + i);
// foreach (var c in "EEFG") dt.Rows.Add(("A B C D " + c).Split()); // optional to generate the table
dt = dt.Rows.Cast<DataRow>()
.GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3])) // group by the first 4 values in each row (you can replace the numbers with the indexes or names of your columns)
.SelectMany(g => g.GroupBy(r => r[4], (k, v) => v.First())) // group each group by the 5th value, and select the first row in each group, to get the distinct rows
.CopyToDataTable(); // optional to copy the rows to a new DataTable
Debug.Print(string.Join("n", dt.AsEnumerable().Select(r => string.Join("t", r.ItemArray)))); // optional to print the result
如果没有其他列,可以缩短它获取每个组中不同的行:
dt = dt.Rows.Cast<DataRow>().GroupBy(r => Tuple.Create(r[0], r[1], r[2], r[3]))
.SelectMany(g => g.Distinct(DataRowComparer.Default)).CopyToDataTable();
运行它并查看k
和dr
值
var groups = dt.AsEnumerable().GroupBy(x => new { col1 = x["col1"], col2 = x["col2"], col3 = x["col3"], col4 = x["col4"] });
foreach (var group in groups)
{
var k = group.Key;
foreach (var dr in group)
{
}
}
链接地址: http://www.djcxy.com/p/68838.html
上一篇: 完全外部连接3在c#中使用Linq的DataTables
下一篇: 如何过滤数据表中的某些DataRows