To reduce the amount of code, is it possible to combine this in one line - where I convert a DataTable column into a string list, but I only want the distinct items in that list (there are multiple columns, so sometimes columns will have multiple values, where one won't):
List<string> column1List = returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).ToList();
var distinctColumn1 = (from distinct1 in column1List select distinct1).Distinct();
The above works, but is an extra line. Since the distinct is an option on the list, I did try:
List<string> column1List = (returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).ToList()).Distinct();
However, that errors, so it appears that distinct can't be called on a list being converted from a DataTable (?).
Just curious if it's possible to convert a DataTable into a string list and only get the distinct values in one line. May not be possible.
Distinct
returns IEnumerable<TSource>
in your case it returns IEnumerable<String>
and you are trying to get the List<String>
in the output.
You need to change the code from
List<string> column1List = (returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).ToList()).Distinct();
List<string> column1List = (returnDataTable.AsEnumerable().Select(x => x["Column1"].ToString()).Distinct().ToList();
使用System.Linq
您可以使用类似这样的东西
my_enumerable.GroupBy(x => x.Column1).Select(x => x.First).ToList()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.