c#datatable在特定条件下选择最后一行 [英] c# datatable select last row on a speicfic condition

查看:1380
本文介绍了c#datatable在特定条件下选择最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datatable有这样的格式的数据



........ IVR ........



......... IVR ........



..... .... IVR ........



......... City1 ......



......... City1 ......



... ...... City1 ......



......... City2 ......

......... City2 ......



... ...... City2 ......



我想要取每个值的最后一行。为了说明,现在是粗体的行



挑战是我在数据表中使用这些三个行。我试图在互联网上搜索,但我不知道这个功能的名称是什么。你可以帮助我吗

解决方案

这可以在一个简单的循环中使用Dictionary来保存发现的行:

  var cRows = new Dictionary< string,DataRow>(StringComparer.InvariantCultureIgnoreCase); 

foreach(在oTable.Rows中的DataRow oRow)
{
var sKey = oRow [KeyValue]。ToString();

if(!cRows.ContainsKey(sKey))
{
cRows.Add(sKey,oRow);
}
else
{
cRows [sKey] = oRow;
}
}

此方法将存储每个唯一值的最后一行在您提名的列中。



将所选行移动到新的DataTable中:

  var oNewTable = oTable.Clone(); 

foreach(var oRow in cRows.Values)
{
oNewTable.Rows.Add(oRow);
}

克隆只是克隆当前表的结构,而不是行。


I have a datatable has data like this format

........ IVR........

.........IVR........

.........IVR........

.........City1......

.........City1......

.........City1......

.........City2......

.........City2......

.........City2......

I want to take the last row of each value. in order words, the rows that are bold now

The challenge is that i wan these three rows in a datatable. I tried to search on internet but i didn't know what is the name of this feature. could you help me please

解决方案

This can be implemented in a simple loop using a Dictionary to hold found rows:

        var cRows = new Dictionary<string, DataRow>(StringComparer.InvariantCultureIgnoreCase);

        foreach (DataRow oRow in oTable.Rows)
        {
            var sKey = oRow["KeyValue"].ToString();

            if (!cRows.ContainsKey(sKey))
            {
                cRows.Add(sKey, oRow);
            }
            else
            {
                cRows[sKey] = oRow;
            }
        }

This approach will store the last row for each unique value in the column that you nominate.

To move the selected rows into a new DataTable:

        var oNewTable = oTable.Clone();

        foreach (var oRow in cRows.Values)
        {
            oNewTable.Rows.Add(oRow);
        }

Clone just clones the structure of the current table, not the rows.

这篇关于c#datatable在特定条件下选择最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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