从.NET 2.0中的DataTable列获取不同的值 [英] Get distinct values from a column of DataTable in .NET 2.0
问题描述
我正在使用.NET Framework 2.0开发的遗留项目。
在这个项目中,我从 DataRowCollection
中通过 ItemNo
列获得不同的值。我只对 ItemNo
感兴趣。 DataRow
由 ItemNo
,数量
和 Date
。
I am working on a legacy project which was developed using .NET Framework 2.0.
In this project, I get distinct values from DataRowCollection
by ItemNo
column. I am only interested in ItemNo
. The DataRow
consist of ItemNo
, Qty
and Date
.
我正在考虑迭代 DataRowCollection
并添加
var items = new List<string>();
foreach (DataRow orderItem in rows)
{
var itemNo = orderItem["ITEMNO"].ToString().Trim();
if(items.Find(delegate(string str) { return str == itemNo ;}) == null)
{
items.Add(itemNo);
}
}
没有LINQ有更好的方法.Net Framework 2.0不像LINQ)
Is there a better way of doing this without LINQ (.Net Framework 2.0 doesnt like LINQ)
推荐答案
// Given a data table:
var dt = new DataTable();
dt.Columns.Add("ITEMNO");
dt.Rows.Add("1 ");
dt.Rows.Add(" 1");
dt.Rows.Add("2");
var dict = new Dictionary<string, bool>();
foreach(DataRow dr in dt.Rows)
{
var itemNo = dr["ITEMNO"].ToString().Trim();
// Take advantage of O(1) lookup:
if (!dict.ContainsKey(itemNo))
{
dict.Add(itemNo, true);
}
}
// Get list from dictionary keys:
var items = new List<string>(dict.Keys);
如果您可以在服务器上安装.Net 3.5,并在应用程序中引用System.Core.dll ,您可以利用将修改上述代码的HashSets:
If you can install .Net 3.5 on the server, and reference System.Core.dll in your application, you can leverage HashSets which would modify the above code to:
var hashSet = new HashSet<string>();
foreach(DataRow dr in dt.Rows)
{
var itemNo = dr["ITEMNO"].ToString().Trim();
// Only unique elements are added to the hash set,
// no need to check for duplicates
hashSet.Add(itemNo);
}
var items = new List<string>(hashSet);
在字典中使用HashSet的好处是毫无意义的,但是我喜欢它,因为我不要在字典中任意布尔值,但是您需要满足.Net 3.5和参考条件。
The benefit of using HashSet over a Dictionary is admittedly trivial, but I'd prefer it since I don't care for the arbitrary bool value in the dictionary, but you'd need to meet the .Net 3.5 and reference requisites.
这篇关于从.NET 2.0中的DataTable列获取不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!