有没有一种内置的方法(可能是LINQ?)从DataTable中获取特定列的所有行值并创建一个HashSet?该列的类型也为String。
我当然可以用循环来做到这一点,但我想知道是否有其他方法?
顺便说一句,我正在使用 .net 3.5。
谢谢,
AJ
使用HashSet<T>构造函数(IEnumerable<T>)
尝试这个,但不确定如何在没有循环的情况下复制数组值作为哈希表值。
string[] strArray = datatable.AsEnumerable().Select(s => s.Field<string>("MyContent")).ToArray<string>();
然后将东西复制到哈希表值中(循环是一种方法)。
希望它能帮到你。
创建了一个项目并将其切换到3.5版本。 有一个简单的一行代码可以完成这个任务(感谢LINQ)。 希望这能帮助未来查看此内容的任何人。
HashSet<string> yourHashSet = new HashSet<string>(dt.AsEnumerable().Select(x => x.Field<string>("YourColumn")))
我的建议是使用LINQ:
IEnumerable<string> values =
dataTable
.Rows
.Cast<DataRow>()
.Select(row => row["ColumnName"])
.Cast<string>();
HashSet<string> hashSet = new HashSet<string>(values);
public static class Extensions
{
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source)
{
return new HashSet<T>(source);
}
}
然后调用
HashSet<string> values = table.AsEnumerable().Select(row => row.Field<string>("Columnname")).ToHashSet();